{"id":13650449,"url":"https://github.com/moleculerjs/moleculer-apollo-server","last_synced_at":"2025-04-05T11:12:29.995Z","repository":{"id":40649857,"uuid":"158609706","full_name":"moleculerjs/moleculer-apollo-server","owner":"moleculerjs","description":":rocket: Apollo GraphQL server for Moleculer","archived":false,"fork":false,"pushed_at":"2024-02-06T07:55:39.000Z","size":959,"stargazers_count":100,"open_issues_count":20,"forks_count":56,"subscribers_count":8,"default_branch":"master","last_synced_at":"2024-10-30T08:49:02.087Z","etag":null,"topics":["apollo-server","graphql-server","hacktoberfest","moleculer"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/moleculerjs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2018-11-21T21:44:52.000Z","updated_at":"2024-05-21T19:03:25.000Z","dependencies_parsed_at":"2023-02-15T12:01:11.452Z","dependency_job_id":"23f0a29f-0032-492b-b144-96d3b0ec9671","html_url":"https://github.com/moleculerjs/moleculer-apollo-server","commit_stats":{"total_commits":140,"total_committers":22,"mean_commits":6.363636363636363,"dds":0.3928571428571429,"last_synced_commit":"f25fe168dd5ac85ca63279d835e4e1aaf15d7372"},"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moleculerjs%2Fmoleculer-apollo-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moleculerjs%2Fmoleculer-apollo-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moleculerjs%2Fmoleculer-apollo-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moleculerjs%2Fmoleculer-apollo-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/moleculerjs","download_url":"https://codeload.github.com/moleculerjs/moleculer-apollo-server/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247294468,"owners_count":20915335,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apollo-server","graphql-server","hacktoberfest","moleculer"],"created_at":"2024-08-02T02:00:36.866Z","updated_at":"2025-04-05T11:12:29.959Z","avatar_url":"https://github.com/moleculerjs.png","language":"JavaScript","funding_links":[],"categories":["Services","JavaScript"],"sub_categories":["Gateway"],"readme":"![Moleculer logo](http://moleculer.services/images/banner.png)\n\n[![Build Status](https://travis-ci.org/moleculerjs/moleculer-apollo-server.svg?branch=master)](https://travis-ci.org/moleculerjs/moleculer-apollo-server)\n[![Coverage Status](https://coveralls.io/repos/github/moleculerjs/moleculer-apollo-server/badge.svg?branch=master)](https://coveralls.io/github/moleculerjs/moleculer-apollo-server?branch=master)\n[![David](https://img.shields.io/david/moleculerjs/moleculer-apollo-server.svg)](https://david-dm.org/moleculerjs/moleculer-apollo-server)\n[![Known Vulnerabilities](https://snyk.io/test/github/moleculerjs/moleculer-apollo-server/badge.svg)](https://snyk.io/test/github/moleculerjs/moleculer-apollo-server)\n\n\n# moleculer-apollo-server [![NPM version](https://img.shields.io/npm/v/moleculer-apollo-server.svg)](https://www.npmjs.com/package/moleculer-apollo-server)\n\n[Apollo GraphQL server](https://www.apollographql.com/docs/apollo-server/) mixin for [Moleculer API Gateway](https://github.com/moleculerjs/moleculer-web)\n\n## Features\n\n## Install\n```\nnpm i moleculer-apollo-server moleculer-web graphql\n```\n\n## Usage\nThis example demonstrates how to setup a Moleculer API Gateway with GraphQL mixin in order to handle incoming GraphQL requests via the default `/graphql` endpoint.\n\n```js\n\"use strict\";\n\nconst ApiGateway \t= require(\"moleculer-web\");\nconst { ApolloService } = require(\"moleculer-apollo-server\");\n\nmodule.exports = {\n    name: \"api\",\n\n    mixins: [\n        // Gateway\n        ApiGateway,\n\n        // GraphQL Apollo Server\n        ApolloService({\n\n            // Global GraphQL typeDefs\n            typeDefs: ``,\n\n            // Global resolvers\n            resolvers: {},\n\n            // API Gateway route options\n            routeOptions: {\n                path: \"/graphql\",\n                cors: true,\n                mappingPolicy: \"restrict\"\n            },\n\n            // https://www.apollographql.com/docs/apollo-server/v2/api/apollo-server.html\n            serverOptions: {\n                tracing: true,\n\n                engine: {\n                    apiKey: process.env.APOLLO_ENGINE_KEY\n                }\n            }\n        })\n    ]\n};\n\n```\n\nStart your Moleculer project, open http://localhost:3000/graphql in your browser to run queries using [graphql-playground](https://github.com/prismagraphql/graphql-playground), or send GraphQL requests directly to the same URL.\n\n\n**Define queries \u0026 mutations in service action definitions**\n\n```js\nmodule.exports = {\n    name: \"greeter\", \n\n    actions: {\n        hello: {\n            graphql: {\n                query: \"hello: String\"\n            },\n            handler(ctx) {\n                return \"Hello Moleculer!\"\n            }\n        },\n        welcome: {\n            params: {\n                name: \"string\"\n            },\n            graphql: {\n                mutation: \"welcome(name: String!): String\"\n            },\n            handler(ctx) {\n                return `Hello ${ctx.params.name}`;\n            }\n        }\n    }\n};\n```\n\n**Generated schema**\n```gql\ntype Mutation {\n  welcome(name: String!): String\n}\n\ntype Query {\n  hello: String\n}\n```\n\n### Resolvers between services\n\n**posts.service.js**\n```js\nmodule.exports = {\n    name: \"posts\",\n    settings: {\n        graphql: {\n            type: `\n                \"\"\"\n                This type describes a post entity.\n                \"\"\"\t\t\t\n                type Post {\n                    id: Int!\n                    title: String!\n                    author: User!\n                    votes: Int!\n                    voters: [User]\n                    createdAt: Timestamp\n                }\n            `,\n            resolvers: {\n                Post: {\n                    author: {\n                        // Call the `users.resolve` action with `id` params\n                        action: \"users.resolve\",\n                        rootParams: {\n                            \"author\": \"id\"\n                        }\n                    },\n                    voters: {\n                        // Call the `users.resolve` action with `id` params\n                        action: \"users.resolve\",\n                        rootParams: {\n                            \"voters\": \"id\"\n                        }\n                    }\n                }\n            }\n        }\n    },\n    actions: {\n        find: {\n            //cache: true,\n            params: {\n                limit: { type: \"number\", optional: true }\n            },\n            graphql: {\n                query: `posts(limit: Int): [Post]`\n            },\n            handler(ctx) {\n                let result = _.cloneDeep(posts);\n                if (ctx.params.limit)\n                    result = posts.slice(0, ctx.params.limit);\n                else\n                    result = posts;\n\n                return _.cloneDeep(result);\n            }\n        },\n\n        findByUser: {\n            params: {\n                userID: \"number\"\n            },\n            handler(ctx) {\n                return _.cloneDeep(posts.filter(post =\u003e post.author == ctx.params.userID));\n            }\n        },\n    }\n};\n```\n\n**users.service.js**\n```js\nmodule.exports = {\n    name: \"users\",\n    settings: {\n        graphql: {\n            type: `\n                \"\"\"\n                This type describes a user entity.\n                \"\"\"\t\t\t\n                type User {\n                    id: Int!\n                    name: String!\n                    birthday: Date\n                    posts(limit: Int): [Post]\n                    postCount: Int\n                }\n            `,\n            resolvers: {\n                User: {\n                    posts: {\n                        // Call the `posts.findByUser` action with `userID` param.\n                        action: \"posts.findByUser\",\n                        rootParams: {\n                            \"id\": \"userID\"\n                        }\n                    },\n                    postCount: {\n                        // Call the \"posts.count\" action\n                        action: \"posts.count\",\n                        // Get `id` value from `root` and put it into `ctx.params.query.author`\n                        rootParams: {\n                            \"id\": \"query.author\"\n                        }\n                    }                    \n                }\n            }\t\t\t\n        }\n    },\n    actions: {\n        find: {\n            //cache: true,\n            params: {\n                limit: { type: \"number\", optional: true }\n            },\n            graphql: {\n                query: \"users(limit: Int): [User]\"\n            },\n            handler(ctx) {\n                let result = _.cloneDeep(users);\n                if (ctx.params.limit)\n                    result = users.slice(0, ctx.params.limit);\n                else\n                    result = users;\n\n                return _.cloneDeep(result);\n            }\n        },\n\n        resolve: {\n            params: {\n                id: [\n                    { type: \"number\" },\n                    { type: \"array\", items: \"number\" }\n                ]\n            },\n            handler(ctx) {\n                if (Array.isArray(ctx.params.id)) {\n                    return _.cloneDeep(ctx.params.id.map(id =\u003e this.findByID(id)));\n                } else {\n                    return _.cloneDeep(this.findByID(ctx.params.id));\n                }\n            }\n        }\n    }\n};\n```\n\n### File Uploads\nmoleculer-apollo-server supports file uploads through the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec). \n\nTo enable uploads, the Upload scalar must be added to the Gateway:\n\n```js\n\"use strict\";\n\nconst ApiGateway \t= require(\"moleculer-web\");\nconst { ApolloService, GraphQLUpload } = require(\"moleculer-apollo-server\");\n\nmodule.exports = {\n    name: \"api\",\n\n    mixins: [\n        // Gateway\n        ApiGateway,\n\n        // GraphQL Apollo Server\n        ApolloService({\n\n            // Global GraphQL typeDefs\n            typeDefs: [\"scalar Upload\"],\n\n            // Global resolvers\n            resolvers: {\n                Upload: GraphQLUpload\n            },\n\n            // API Gateway route options\n            routeOptions: {\n                path: \"/graphql\",\n                cors: true,\n                mappingPolicy: \"restrict\"\n            },\n\n            // https://www.apollographql.com/docs/apollo-server/v2/api/apollo-server.html\n            serverOptions: {\n                tracing: true,\n\n                engine: {\n                    apiKey: process.env.APOLLO_ENGINE_KEY\n                }\n            }\n        })\n    ]\n};\n\n```\n\nThen a mutation can be created which accepts an Upload argument. The `fileUploadArg` property must be set to the mutation's argument name so that moleculer-apollo-server knows where to expect a file upload. When the mutation's action handler is called, `ctx.params` will be a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) which can be used to read the contents of the uploaded file (or pipe the contents into a Writable Stream). File metadata will be made available in `ctx.meta.$fileInfo`.\n\n**files.service.js**\n```js\nmodule.exports = {\n    name: \"files\",\n    settings: {\n        graphql: {\n            type: `\n                \"\"\"\n                This type describes a File entity.\n                \"\"\"\t\t\t\n                type File {\n                    filename: String!\n                    encoding: String!\n                    mimetype: String!\n                }\n            `\n        }\n    },\n    actions: {\n        uploadFile: {\n            graphql: {\n                mutation: \"uploadFile(file: Upload!): File!\",\n                fileUploadArg: \"file\",\n            },\n            async handler(ctx) {\n                const fileChunks = [];\n                for await (const chunk of ctx.params) {\n                    fileChunks.push(chunk);\n                }\n                const fileContents = Buffer.concat(fileChunks);\n                // Do something with file contents\n                \n                // Additional arguments:\n                this.logger.info(\"Additional arguments:\", ctx.meta.$args);\n\n                return ctx.meta.$fileInfo;\n            }\n        }\n    }\n};\n```\n\nTo accept multiple uploaded files in a single request, the mutation can be changed to accept an array of `Upload`s and return an array of results. The action handler will then be called once for each uploaded file, and the results will be combined into an array automatically with results in the same order as the provided files.\n\n```js\n...\ngraphql: {\n    mutation: \"upload(file: [Upload!]!): [File!]!\",\n    fileUploadArg: \"file\"\n}\n...\n```\n\n### Dataloader\nmoleculer-apollo-server supports [DataLoader](https://github.com/graphql/dataloader) via configuration in the resolver definition.\nThe called action must be compatible with DataLoader semantics -- that is, it must accept params with an array property and return an array of the same size,\nwith the results in the same order as they were provided.\n\nTo activate DataLoader for a resolver, simply add `dataLoader: true` to the resolver's property object in the `resolvers` property of the service's `graphql` property:\n\n```js\nsettings: {\n\tgraphql: {\n\t\tresolvers: {\n\t\t\tPost: {\n\t\t\t\tauthor: {\n\t\t\t\t\taction: \"users.resolve\",\n\t\t\t\t\tdataLoader: true,\n\t\t\t\t\trootParams: {\n\t\t\t\t\t\tauthor: \"id\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tvoters: {\n\t\t\t\t\taction: \"users.resolve\",\n\t\t\t\t\tdataLoader: true,\n\t\t\t\t\trootParams: {\n\t\t\t\t\t\tvoters: \"id\",\n\t\t\t\t\t},\n\t\t\t\t},\n                ...\n```\nSince DataLoader only expects a single value to be loaded at a time, only one `rootParams` key/value pairing will be utilized, but `params` and GraphQL child arguments work properly.\n\nYou can also specify [options](https://github.com/graphql/dataloader#api) for construction of the DataLoader in the called action definition's `graphql` property.  This is useful for setting things like `maxBatchSize'.\n\n```js\nresolve: {\n\tparams: {\n\t\tid: [{ type: \"number\" }, { type: \"array\", items: \"number\" }],\n\t\tgraphql: { dataLoaderOptions: { maxBatchSize: 100 } },\n\t},\n\thandler(ctx) {\n\t\tthis.logger.debug(\"resolve action called.\", { params: ctx.params });\n\t\tif (Array.isArray(ctx.params.id)) {\n\t\t\treturn _.cloneDeep(ctx.params.id.map(id =\u003e this.findByID(id)));\n\t\t} else {\n\t\t\treturn _.cloneDeep(this.findByID(ctx.params.id));\n\t\t}\n\t},\n},\n```\nIt is unlikely that setting any of the options which accept a function will work properly unless you are running moleculer in a single-node environment.  This is because the functions will not serialize and be run by the moleculer-web Api Gateway.\n\n## Examples\n\n- [Simple](examples/simple/index.js)\n  - `npm run dev`\n- [File Upload](examples/upload/index.js)\n  - `npm run dev upload`\n  - See [here](https://github.com/jaydenseric/graphql-multipart-request-spec#curl-request) for information about how to create a file upload request\n- [Full](examples/full/index.js)\n  - `npm run dev full`\n- [Full With Dataloader](examples/full/index.js)\n  - set `DATALOADER` environment variable to `\"true\"`\n  - `npm run dev full`\n# Test\n```\n$ npm test\n```\n\nIn development with watching\n\n```\n$ npm run ci\n```\n\n# Contribution\nPlease send pull requests improving the usage and fixing bugs, improving documentation and providing better examples, or providing some testing, because these things are important.\n\n# License\nThe project is available under the [MIT license](https://tldrlegal.com/license/mit-license).\n\n# Contact\nCopyright (c) 2020 MoleculerJS\n\n[![@moleculerjs](https://img.shields.io/badge/github-moleculerjs-green.svg)](https://github.com/moleculerjs) [![@MoleculerJS](https://img.shields.io/badge/twitter-MoleculerJS-blue.svg)](https://twitter.com/MoleculerJS)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoleculerjs%2Fmoleculer-apollo-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmoleculerjs%2Fmoleculer-apollo-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoleculerjs%2Fmoleculer-apollo-server/lists"}