### Install moleculer-apollo-server Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Install the necessary packages for moleculer-apollo-server, moleculer-web, and graphql. ```bash npm i moleculer-apollo-server moleculer-web graphql ``` -------------------------------- ### Generated GraphQL Schema Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md This is an example of the GraphQL schema automatically generated based on the service actions defined with the 'graphql' property. ```graphql type Mutation { welcome(name: String!): String } type Query { hello: String } ``` -------------------------------- ### Define GraphQL Queries and Mutations in Service Actions Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Define GraphQL queries and mutations directly within Moleculer service action definitions using the 'graphql' property. This example shows a 'hello' query and a 'welcome' mutation. ```javascript module.exports = { name: "greeter", actions: { hello: { graphql: { query: "hello: String" }, handler(ctx) { return "Hello Moleculer!" } }, welcome: { params: { name: "string" }, graphql: { mutation: "welcome(name: String!): String" }, handler(ctx) { return `Hello ${ctx.params.name}`; } } } }; ``` -------------------------------- ### Setup API Gateway with ApolloService Mixin Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Configure the Moleculer API Gateway to handle GraphQL requests using the ApolloService mixin. This sets up the default '/graphql' endpoint. ```javascript "use strict"; const ApiGateway = require("moleculer-web"); const { ApolloService } = require("moleculer-apollo-server"); module.exports = { name: "api", mixins: [ // Gateway ApiGateway, // GraphQL Apollo Server ApolloService({ // Global GraphQL typeDefs typeDefs: ``, // Global resolvers resolvers: {}, // API Gateway route options routeOptions: { path: "/graphql", cors: true, mappingPolicy: "restrict" }, // https://www.apollographql.com/docs/apollo-server/api/apollo-server#options serverOptions: {} }) ] }; ``` -------------------------------- ### Define Post Type and Resolvers in posts.service.js Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Defines the GraphQL 'Post' type and configures resolvers to fetch related 'author' and 'voters' by calling the 'users.resolve' action. This setup is useful for linking entities across services. ```javascript module.exports = { name: "posts", settings: { graphql: { type: ` """ This type describes a post entity. """ type Post { id: Int! title: String! author: User! votes: Int! voters: [User] createdAt: Timestamp } `, resolvers: { Post: { author: { // Call the `users.resolve` action with `id` params action: "users.resolve", rootParams: { "author": "id" } }, voters: { // Call the `users.resolve` action with `id` params action: "users.resolve", rootParams: { "voters": "id" } } } } } }, actions: { find: { //cache: true, params: { limit: { type: "number", optional: true } }, graphql: { query: `posts(limit: Int): [Post]` }, handler(ctx) { let result = _.cloneDeep(posts); if (ctx.params.limit) result = posts.slice(0, ctx.params.limit); else result = posts; return _.cloneDeep(result); } }, findByUser: { params: { userID: "number" }, handler(ctx) { return _.cloneDeep(posts.filter(post => post.author == ctx.params.userID)); } }, } }; ``` -------------------------------- ### Define User Type and Resolvers in users.service.js Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Defines the GraphQL 'User' type and configures resolvers for 'posts' and 'postCount'. It demonstrates calling 'posts.findByUser' to retrieve a user's posts and 'posts.count' to get the number of posts by a specific author. ```javascript module.exports = { name: "users", settings: { graphql: { type: ` """ This type describes a user entity. """ type User { id: Int! name: String! birthday: Date posts(limit: Int): [Post] postCount: Int } `, resolvers: { User: { posts: { // Call the `posts.findByUser` action with `userID` param. action: "posts.findByUser", rootParams: { "id": "userID" } }, postCount: { // Call the "posts.count" action action: "posts.count", // Get `id` value from `root` and put it into `ctx.params.query.author` rootParams: { "id": "query.author" } } } } } }, actions: { find: { //cache: true, params: { limit: { type: "number", optional: true } }, graphql: { query: "users(limit: Int): [User]" }, handler(ctx) { let result = _.cloneDeep(users); if (ctx.params.limit) result = users.slice(0, ctx.params.limit); else result = users; return _.cloneDeep(result); } }, resolve: { params: { id: [ { type: "number" }, { type: "array", items: "number" } ] }, handler(ctx) { if (Array.isArray(ctx.params.id)) { return _.cloneDeep(ctx.params.id.map(id => this.findByID(id))); } else { return _.cloneDeep(this.findByID(ctx.params.id)); } } } } }; ``` -------------------------------- ### Configure DataLoader Options in Action Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md DataLoader options, such as `maxBatchSize`, can be specified in the called action definition's `graphql` property. The action handler must be able to process both single IDs and arrays of IDs. ```javascript resolve: { params: { id: [{ type: "number" }, { type: "array", items: "number" }], graphql: { dataLoaderOptions: { maxBatchSize: 100 } }, }, handler(ctx) { this.logger.debug("resolve action called.", { params: ctx.params }); if (Array.isArray(ctx.params.id)) { return _.cloneDeep(ctx.params.id.map(id => this.findByID(id))); } else { return _.cloneDeep(this.findByID(ctx.params.id)); } }, }, ``` -------------------------------- ### Enable DataLoader for Resolver Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md To enable DataLoader for a resolver, add `dataLoader: true` to the resolver's property object within the `resolvers` configuration of the service's `graphql` property. This requires the called action to accept params with an array property and return an array of the same size. ```javascript module.exports = { settings: { graphql: { resolvers: { Post: { author: { action: "users.resolve", dataLoader: true, rootParams: { author: "id", }, }, voters: { action: "users.resolve", dataLoader: true, rootParams: { voters: "id", }, }, // ... } } } } }; ``` -------------------------------- ### users.resolve Action Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Resolves one or more user entities by their IDs. This action is used internally by resolvers. ```APIDOC ## users.resolve ### Description Resolves user(s) by their unique identifier(s). ### Parameters #### Path Parameters - **id** (number | number[]) - Required - The ID or an array of IDs of the user(s) to resolve. ### Response #### Success Response (200) - **User** (User) or **[User]** ([User]) - The resolved user object or an array of user objects. ### Request Example ```json { "id": 101 } ``` ### Request Example (Array) ```json { "id": [101, 102] } ``` ### Response Example ```json { "id": 101, "name": "John Doe" } ``` ### Response Example (Array) ```json [ { "id": 101, "name": "John Doe" }, { "id": 102, "name": "Jane Smith" } ] ``` ``` -------------------------------- ### Posts Service GraphQL API Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Exposes GraphQL queries for fetching post data, including a `posts` query that can be filtered by a limit. ```APIDOC ## posts ### Description Fetches a list of posts, optionally limited to a specified number. ### Method GET ### Endpoint /graphql ### Parameters #### Query Parameters - **limit** (Int) - Optional - The maximum number of posts to return. ### Response #### Success Response (200) - **posts** ([Post]) - A list of Post objects. ### Request Example ```graphql query { posts(limit: 10) { id title author { id name } votes createdAt } } ``` ### Response Example ```json { "data": { "posts": [ { "id": 1, "title": "First Post", "author": { "id": 101, "name": "John Doe" }, "votes": 5, "createdAt": "2023-10-27T10:00:00Z" } ] } } ``` ``` -------------------------------- ### Users Service GraphQL API Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Exposes GraphQL queries for fetching user data, including a `users` query that can be filtered by a limit. ```APIDOC ## users ### Description Fetches a list of users, optionally limited to a specified number. ### Method GET ### Endpoint /graphql ### Parameters #### Query Parameters - **limit** (Int) - Optional - The maximum number of users to return. ### Response #### Success Response (200) - **users** ([User]) - A list of User objects. ### Request Example ```graphql query { users(limit: 5) { id name birthday } } ``` ### Response Example ```json { "data": { "users": [ { "id": 101, "name": "John Doe", "birthday": "1990-05-15" } ] } } ``` ``` -------------------------------- ### User.postCount Resolver Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Resolves the `postCount` field for a User type by calling the `posts.count` action. ```APIDOC ## User.postCount ### Description Retrieves the total number of posts authored by a specific user. ### Method GET ### Endpoint /graphql ### Response #### Success Response (200) - **postCount** (Int) - The total count of posts authored by the user. ### Request Example ```graphql query { users { id postCount } } ``` ### Response Example ```json { "data": { "users": [ { "id": 101, "postCount": 15 } ] } } ``` ``` -------------------------------- ### User.posts Resolver Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Resolves the `posts` field for a User type by calling the `posts.findByUser` action. ```APIDOC ## User.posts ### Description Retrieves all posts authored by a specific user. ### Method GET ### Endpoint /graphql ### Parameters #### Query Parameters - **userID** (Int) - Required - The ID of the user whose posts are to be fetched. ### Response #### Success Response (200) - **posts** ([Post]) - A list of Post objects authored by the user. ### Request Example ```graphql query { users { id posts(limit: 3) { id title } } } ``` ### Response Example ```json { "data": { "users": [ { "id": 101, "posts": [ { "id": 1, "title": "First Post" }, { "id": 2, "title": "Second Post" } ] } ] } } ``` ``` -------------------------------- ### Post.author Resolver Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Resolves the `author` field for a Post type by calling the `users.resolve` action. ```APIDOC ## Post.author ### Description Retrieves the author of a specific post. ### Method GET ### Endpoint /graphql ### Response #### Success Response (200) - **author** (User) - The User object representing the author of the post. ### Request Example ```graphql query { posts { id author { id name } } } ``` ### Response Example ```json { "data": { "posts": [ { "id": 1, "author": { "id": 101, "name": "John Doe" } } ] } } ``` ``` -------------------------------- ### Post.voters Resolver Source: https://github.com/moleculerjs/moleculer-apollo-server/blob/master/README.md Resolves the `voters` field for a Post type by calling the `users.resolve` action. ```APIDOC ## Post.voters ### Description Retrieves the list of users who have voted on a specific post. ### Method GET ### Endpoint /graphql ### Response #### Success Response (200) - **voters** ([User]) - A list of User objects representing the voters. ### Request Example ```graphql query { posts { id voters { id name } } } ``` ### Response Example ```json { "data": { "posts": [ { "id": 1, "voters": [ { "id": 101, "name": "John Doe" }, { "id": 102, "name": "Jane Smith" } ] } ] } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.