@steedos/moleculer-apollo-server 3.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ version: "2"
2
+
3
+ checks:
4
+ argument-count:
5
+ enabled: false
6
+ complex-logic:
7
+ enabled: false
8
+ file-lines:
9
+ enabled: false
10
+ method-complexity:
11
+ enabled: false
12
+ method-count:
13
+ enabled: false
14
+ method-lines:
15
+ enabled: false
16
+ nested-control-flow:
17
+ enabled: false
18
+ return-statements:
19
+ enabled: false
20
+ similar-code:
21
+ enabled: false
22
+ identical-code:
23
+ enabled: false
24
+
25
+ plugins:
26
+ duplication:
27
+ enabled: false
28
+ config:
29
+ languages:
30
+ - javascript
31
+ eslint:
32
+ enabled: true
33
+ channel: "eslint-4"
34
+ fixme:
35
+ enabled: true
36
+
37
+ exclude_paths:
38
+ - test/
39
+ - benchmark/
40
+ - examples/
41
+ - typings/
package/.editorconfig ADDED
@@ -0,0 +1,31 @@
1
+ # EditorConfig helps developers define and maintain consistent
2
+ # coding styles between different editors and IDEs
3
+ # editorconfig.org
4
+
5
+ root = true
6
+
7
+ [*]
8
+
9
+ # Change these settings to your own preference
10
+ indent_style = tab
11
+ indent_size = 4
12
+ space_after_anon_function = true
13
+
14
+ # We recommend you to keep these unchanged
15
+ end_of_line = lf
16
+ charset = utf-8
17
+ trim_trailing_whitespace = true
18
+ insert_final_newline = true
19
+
20
+ [*.md]
21
+ trim_trailing_whitespace = false
22
+ indent_style = space
23
+ indent_size = 4
24
+
25
+ [{package,bower}.json]
26
+ indent_style = space
27
+ indent_size = 2
28
+
29
+ [*.js]
30
+ quote_type = "double"
31
+ indent_size = unset
package/.eslintignore ADDED
@@ -0,0 +1,3 @@
1
+ ### file include overrides
2
+ # root configuration files (e.g. .eslintrc.js)
3
+ !.*.js
package/.eslintrc.js ADDED
@@ -0,0 +1,31 @@
1
+ module.exports = {
2
+ env: {
3
+ node: true,
4
+ commonjs: true,
5
+ es6: true,
6
+ jquery: false,
7
+ jest: true,
8
+ jasmine: true,
9
+ },
10
+ extends: ["eslint:recommended", "plugin:security/recommended", "plugin:prettier/recommended"],
11
+ parserOptions: {
12
+ sourceType: "module",
13
+ ecmaVersion: 2018,
14
+ },
15
+ plugins: ["node", "promise", "security"],
16
+ rules: {
17
+ semi: ["error", "always"],
18
+ "no-var": ["error"],
19
+ "no-console": ["error"],
20
+ "no-unused-vars": ["warn"],
21
+ "no-trailing-spaces": ["error"],
22
+ "no-alert": 0,
23
+ "no-shadow": 0,
24
+ "security/detect-object-injection": ["off"],
25
+ "security/detect-non-literal-require": ["off"],
26
+ "security/detect-non-literal-fs-filename": ["off"],
27
+ "no-process-exit": ["off"],
28
+ "node/no-unpublished-require": 0,
29
+ "require-atomic-updates": 0,
30
+ },
31
+ };
package/.prettierrc.js ADDED
@@ -0,0 +1,10 @@
1
+ module.exports = {
2
+ useTabs: true,
3
+ printWidth: 100,
4
+ tabWidth: 4,
5
+ trailingComma: "es5",
6
+ bracketSpacing: true,
7
+ arrowParens: "avoid",
8
+ semi: true,
9
+ singleQuote: false,
10
+ };
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 MoleculerJS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,448 @@
1
+ ![Moleculer logo](http://moleculer.services/images/banner.png)
2
+
3
+ [![Build Status](https://travis-ci.org/moleculerjs/moleculer-apollo-server.svg?branch=master)](https://travis-ci.org/moleculerjs/moleculer-apollo-server)
4
+ [![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)
5
+ [![David](https://img.shields.io/david/moleculerjs/moleculer-apollo-server.svg)](https://david-dm.org/moleculerjs/moleculer-apollo-server)
6
+ [![Known Vulnerabilities](https://snyk.io/test/github/moleculerjs/moleculer-apollo-server/badge.svg)](https://snyk.io/test/github/moleculerjs/moleculer-apollo-server)
7
+
8
+
9
+ # moleculer-apollo-server [![NPM version](https://img.shields.io/npm/v/moleculer-apollo-server.svg)](https://www.npmjs.com/package/moleculer-apollo-server)
10
+
11
+ [Apollo GraphQL server](https://www.apollographql.com/docs/apollo-server/) mixin for [Moleculer API Gateway](https://github.com/moleculerjs/moleculer-web)
12
+
13
+ ## Features
14
+
15
+ ## Install
16
+ ```
17
+ npm i moleculer-apollo-server moleculer-web graphql
18
+ ```
19
+
20
+ ## Usage
21
+ This example demonstrates how to setup a Moleculer API Gateway with GraphQL mixin in order to handle incoming GraphQL requests via the default `/graphql` endpoint.
22
+
23
+ ```js
24
+ "use strict";
25
+
26
+ const ApiGateway = require("moleculer-web");
27
+ const { ApolloService } = require("moleculer-apollo-server");
28
+
29
+ module.exports = {
30
+ name: "api",
31
+
32
+ mixins: [
33
+ // Gateway
34
+ ApiGateway,
35
+
36
+ // GraphQL Apollo Server
37
+ ApolloService({
38
+
39
+ // Global GraphQL typeDefs
40
+ typeDefs: ``,
41
+
42
+ // Global resolvers
43
+ resolvers: {},
44
+
45
+ // API Gateway route options
46
+ routeOptions: {
47
+ path: "/graphql",
48
+ cors: true,
49
+ mappingPolicy: "restrict"
50
+ },
51
+
52
+ // https://www.apollographql.com/docs/apollo-server/v2/api/apollo-server.html
53
+ serverOptions: {
54
+ tracing: true,
55
+
56
+ engine: {
57
+ apiKey: process.env.APOLLO_ENGINE_KEY
58
+ }
59
+ }
60
+ })
61
+ ]
62
+ };
63
+
64
+ ```
65
+
66
+ Start 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.
67
+
68
+
69
+ **Define queries & mutations in service action definitions**
70
+
71
+ ```js
72
+ module.exports = {
73
+ name: "greeter",
74
+
75
+ actions: {
76
+ hello: {
77
+ graphql: {
78
+ query: "hello: String"
79
+ },
80
+ handler(ctx) {
81
+ return "Hello Moleculer!"
82
+ }
83
+ },
84
+ welcome: {
85
+ params: {
86
+ name: "string"
87
+ },
88
+ graphql: {
89
+ mutation: "welcome(name: String!): String"
90
+ },
91
+ handler(ctx) {
92
+ return `Hello ${ctx.params.name}`;
93
+ }
94
+ }
95
+ }
96
+ };
97
+ ```
98
+
99
+ **Generated schema**
100
+ ```gql
101
+ type Mutation {
102
+ welcome(name: String!): String
103
+ }
104
+
105
+ type Query {
106
+ hello: String
107
+ }
108
+ ```
109
+
110
+ ### Resolvers between services
111
+
112
+ **posts.service.js**
113
+ ```js
114
+ module.exports = {
115
+ name: "posts",
116
+ settings: {
117
+ graphql: {
118
+ type: `
119
+ """
120
+ This type describes a post entity.
121
+ """
122
+ type Post {
123
+ id: Int!
124
+ title: String!
125
+ author: User!
126
+ votes: Int!
127
+ voters: [User]
128
+ createdAt: Timestamp
129
+ }
130
+ `,
131
+ resolvers: {
132
+ Post: {
133
+ author: {
134
+ // Call the `users.resolve` action with `id` params
135
+ action: "users.resolve",
136
+ rootParams: {
137
+ "author": "id"
138
+ }
139
+ },
140
+ voters: {
141
+ // Call the `users.resolve` action with `id` params
142
+ action: "users.resolve",
143
+ rootParams: {
144
+ "voters": "id"
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ },
151
+ actions: {
152
+ find: {
153
+ //cache: true,
154
+ params: {
155
+ limit: { type: "number", optional: true }
156
+ },
157
+ graphql: {
158
+ query: `posts(limit: Int): [Post]`
159
+ },
160
+ handler(ctx) {
161
+ let result = _.cloneDeep(posts);
162
+ if (ctx.params.limit)
163
+ result = posts.slice(0, ctx.params.limit);
164
+ else
165
+ result = posts;
166
+
167
+ return _.cloneDeep(result);
168
+ }
169
+ },
170
+
171
+ findByUser: {
172
+ params: {
173
+ userID: "number"
174
+ },
175
+ handler(ctx) {
176
+ return _.cloneDeep(posts.filter(post => post.author == ctx.params.userID));
177
+ }
178
+ },
179
+ }
180
+ };
181
+ ```
182
+
183
+ **users.service.js**
184
+ ```js
185
+ module.exports = {
186
+ name: "users",
187
+ settings: {
188
+ graphql: {
189
+ type: `
190
+ """
191
+ This type describes a user entity.
192
+ """
193
+ type User {
194
+ id: Int!
195
+ name: String!
196
+ birthday: Date
197
+ posts(limit: Int): [Post]
198
+ postCount: Int
199
+ }
200
+ `,
201
+ resolvers: {
202
+ User: {
203
+ posts: {
204
+ // Call the `posts.findByUser` action with `userID` param.
205
+ action: "posts.findByUser",
206
+ rootParams: {
207
+ "id": "userID"
208
+ }
209
+ },
210
+ postCount: {
211
+ // Call the "posts.count" action
212
+ action: "posts.count",
213
+ // Get `id` value from `root` and put it into `ctx.params.query.author`
214
+ rootParams: {
215
+ "id": "query.author"
216
+ }
217
+ }
218
+ }
219
+ }
220
+ }
221
+ },
222
+ actions: {
223
+ find: {
224
+ //cache: true,
225
+ params: {
226
+ limit: { type: "number", optional: true }
227
+ },
228
+ graphql: {
229
+ query: "users(limit: Int): [User]"
230
+ },
231
+ handler(ctx) {
232
+ let result = _.cloneDeep(users);
233
+ if (ctx.params.limit)
234
+ result = users.slice(0, ctx.params.limit);
235
+ else
236
+ result = users;
237
+
238
+ return _.cloneDeep(result);
239
+ }
240
+ },
241
+
242
+ resolve: {
243
+ params: {
244
+ id: [
245
+ { type: "number" },
246
+ { type: "array", items: "number" }
247
+ ]
248
+ },
249
+ handler(ctx) {
250
+ if (Array.isArray(ctx.params.id)) {
251
+ return _.cloneDeep(ctx.params.id.map(id => this.findByID(id)));
252
+ } else {
253
+ return _.cloneDeep(this.findByID(ctx.params.id));
254
+ }
255
+ }
256
+ }
257
+ }
258
+ };
259
+ ```
260
+
261
+ ### File Uploads
262
+ moleculer-apollo-server supports file uploads through the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec).
263
+
264
+ To enable uploads, the Upload scalar must be added to the Gateway:
265
+
266
+ ```js
267
+ "use strict";
268
+
269
+ const ApiGateway = require("moleculer-web");
270
+ const { ApolloService, GraphQLUpload } = require("moleculer-apollo-server");
271
+
272
+ module.exports = {
273
+ name: "api",
274
+
275
+ mixins: [
276
+ // Gateway
277
+ ApiGateway,
278
+
279
+ // GraphQL Apollo Server
280
+ ApolloService({
281
+
282
+ // Global GraphQL typeDefs
283
+ typeDefs: ["scalar Upload"],
284
+
285
+ // Global resolvers
286
+ resolvers: {
287
+ Upload: GraphQLUpload
288
+ },
289
+
290
+ // API Gateway route options
291
+ routeOptions: {
292
+ path: "/graphql",
293
+ cors: true,
294
+ mappingPolicy: "restrict"
295
+ },
296
+
297
+ // https://www.apollographql.com/docs/apollo-server/v2/api/apollo-server.html
298
+ serverOptions: {
299
+ tracing: true,
300
+
301
+ engine: {
302
+ apiKey: process.env.APOLLO_ENGINE_KEY
303
+ }
304
+ }
305
+ })
306
+ ]
307
+ };
308
+
309
+ ```
310
+
311
+ Then 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`.
312
+
313
+ **files.service.js**
314
+ ```js
315
+ module.exports = {
316
+ name: "files",
317
+ settings: {
318
+ graphql: {
319
+ type: `
320
+ """
321
+ This type describes a File entity.
322
+ """
323
+ type File {
324
+ filename: String!
325
+ encoding: String!
326
+ mimetype: String!
327
+ }
328
+ `
329
+ }
330
+ },
331
+ actions: {
332
+ uploadFile: {
333
+ graphql: {
334
+ mutation: "uploadFile(file: Upload!): File!",
335
+ fileUploadArg: "file",
336
+ },
337
+ async handler(ctx) {
338
+ const fileChunks = [];
339
+ for await (const chunk of ctx.params) {
340
+ fileChunks.push(chunk);
341
+ }
342
+ const fileContents = Buffer.concat(fileChunks);
343
+ // Do something with file contents
344
+
345
+ // Additional arguments:
346
+ this.logger.info("Additional arguments:", ctx.meta.$args);
347
+
348
+ return ctx.meta.$fileInfo;
349
+ }
350
+ }
351
+ }
352
+ };
353
+ ```
354
+
355
+ To 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.
356
+
357
+ ```js
358
+ ...
359
+ graphql: {
360
+ mutation: "upload(file: [Upload!]!): [File!]!",
361
+ fileUploadArg: "file"
362
+ }
363
+ ...
364
+ ```
365
+
366
+ ### Dataloader
367
+ moleculer-apollo-server supports [DataLoader](https://github.com/graphql/dataloader) via configuration in the resolver definition.
368
+ The 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,
369
+ with the results in the same order as they were provided.
370
+
371
+ To 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:
372
+
373
+ ```js
374
+ settings: {
375
+ graphql: {
376
+ resolvers: {
377
+ Post: {
378
+ author: {
379
+ action: "users.resolve",
380
+ dataLoader: true,
381
+ rootParams: {
382
+ author: "id",
383
+ },
384
+ },
385
+ voters: {
386
+ action: "users.resolve",
387
+ dataLoader: true,
388
+ rootParams: {
389
+ voters: "id",
390
+ },
391
+ },
392
+ ...
393
+ ```
394
+ Since 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.
395
+
396
+ You 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'.
397
+
398
+ ```js
399
+ resolve: {
400
+ params: {
401
+ id: [{ type: "number" }, { type: "array", items: "number" }],
402
+ graphql: { dataLoaderOptions: { maxBatchSize: 100 } },
403
+ },
404
+ handler(ctx) {
405
+ this.logger.debug("resolve action called.", { params: ctx.params });
406
+ if (Array.isArray(ctx.params.id)) {
407
+ return _.cloneDeep(ctx.params.id.map(id => this.findByID(id)));
408
+ } else {
409
+ return _.cloneDeep(this.findByID(ctx.params.id));
410
+ }
411
+ },
412
+ },
413
+ ```
414
+ It 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.
415
+
416
+ ## Examples
417
+
418
+ - [Simple](examples/simple/index.js)
419
+ - `npm run dev`
420
+ - [File Upload](examples/upload/index.js)
421
+ - `npm run dev upload`
422
+ - See [here](https://github.com/jaydenseric/graphql-multipart-request-spec#curl-request) for information about how to create a file upload request
423
+ - [Full](examples/full/index.js)
424
+ - `npm run dev full`
425
+ - [Full With Dataloader](examples/full/index.js)
426
+ - set `DATALOADER` environment variable to `"true"`
427
+ - `npm run dev full`
428
+ # Test
429
+ ```
430
+ $ npm test
431
+ ```
432
+
433
+ In development with watching
434
+
435
+ ```
436
+ $ npm run ci
437
+ ```
438
+
439
+ # Contribution
440
+ Please send pull requests improving the usage and fixing bugs, improving documentation and providing better examples, or providing some testing, because these things are important.
441
+
442
+ # License
443
+ The project is available under the [MIT license](https://tldrlegal.com/license/mit-license).
444
+
445
+ # Contact
446
+ Copyright (c) 2020 MoleculerJS
447
+
448
+ [![@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)
package/index.d.ts ADDED
@@ -0,0 +1,108 @@
1
+ declare module "moleculer-apollo-server" {
2
+ import { ServiceSchema, Context } from "moleculer";
3
+ import { Config } from "apollo-server-core";
4
+ import { OptionsUrlencoded } from "body-parser";
5
+ import { SchemaDirectiveVisitor, IResolvers } from "graphql-tools";
6
+
7
+ export {
8
+ GraphQLExtension,
9
+ gql,
10
+ ApolloError,
11
+ toApolloError,
12
+ SyntaxError,
13
+ ValidationError,
14
+ AuthenticationError,
15
+ ForbiddenError,
16
+ UserInputError,
17
+ defaultPlaygroundOptions,
18
+ } from "apollo-server-core";
19
+
20
+ export { GraphQLUpload } from "graphql-upload";
21
+
22
+ export * from "graphql-tools";
23
+
24
+ export interface ApolloServerOptions {
25
+ path: string;
26
+ disableHealthCheck: boolean;
27
+ onHealthCheck: () => {};
28
+ }
29
+
30
+ export class ApolloServer {
31
+ createGraphQLServerOptions(req: any, res: any): Promise<any>;
32
+ createHandler(options: ApolloServerOptions): void;
33
+ supportsUploads(): boolean;
34
+ supportsSubscriptions(): boolean;
35
+ }
36
+
37
+ export interface ActionResolverSchema {
38
+ action: string;
39
+ rootParams?: {
40
+ [key: string]: string;
41
+ };
42
+ dataLoader?: boolean;
43
+ nullIfError?: boolean;
44
+ skipNullKeys?: boolean;
45
+ params?: { [key: string]: any };
46
+ }
47
+
48
+ export interface ServiceResolverSchema {
49
+ [key: string]: {
50
+ [key: string]: ActionResolverSchema;
51
+ };
52
+ }
53
+
54
+ type CorsMethods = "GET" | "POST" | "PUT" | "DELETE" | "OPTIONS";
55
+
56
+ export interface ServiceRouteCorsOptions {
57
+ origin?: string | string[];
58
+ methods?: CorsMethods | CorsMethods[];
59
+ allowedHeaders?: string[];
60
+ exposedHeaders?: string[];
61
+ credentials?: boolean;
62
+ maxAge?: number;
63
+ }
64
+
65
+ export interface ServiceRouteOptions {
66
+ path?: string;
67
+ use?: any[];
68
+ etag?: boolean;
69
+ whitelist?: string[];
70
+ authorization?: boolean;
71
+ camelCaseNames?: boolean;
72
+ aliases?: {
73
+ [key: string]: any; // Should discuss more on this. string | AliasSchema, ...
74
+ };
75
+ bodyParsers?: {
76
+ json: boolean;
77
+ urlencoded: OptionsUrlencoded;
78
+ };
79
+ cors?: boolean | ServiceRouteCorsOptions;
80
+ mappingPolicy?: "all" | "restrict";
81
+ authentication?: boolean;
82
+ callOptions?: {
83
+ timeout: number;
84
+ fallbackResponse?: any;
85
+ };
86
+ onBeforeCall?: (ctx: Context, route: any, req: any, res: any) => Promise<any>;
87
+ onAfterCall?: (ctx: Context, route: any, req: any, res: any, data: any) => Promise<any>;
88
+ }
89
+
90
+ export interface ApolloServiceOptions {
91
+ typeDefs?: string | string[];
92
+ resolvers?: ServiceResolverSchema | IResolvers | Array<IResolvers>;
93
+ schemaDirectives?: {
94
+ [name: string]: typeof SchemaDirectiveVisitor;
95
+ };
96
+ routeOptions?: ServiceRouteOptions;
97
+ serverOptions?: Config;
98
+ checkActionVisibility?: boolean;
99
+ autoUpdateSchema?: boolean;
100
+ }
101
+
102
+ export function ApolloService(options: ApolloServiceOptions): ServiceSchema;
103
+
104
+ export function moleculerGql<T>(
105
+ typeString: TemplateStringsArray | string,
106
+ ...placeholders: T[]
107
+ ): string;
108
+ }