@teambit/graphql 0.0.574 → 0.0.578

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.
@@ -2,7 +2,7 @@
2
2
  import { Harmony, SlotRegistry } from '@teambit/harmony';
3
3
  import { Logger, LoggerMain } from '@teambit/logger';
4
4
  import { Express } from 'express';
5
- import { PubSub } from 'graphql-subscriptions';
5
+ import { PubSubEngine } from 'graphql-subscriptions';
6
6
  import { Server } from 'http';
7
7
  import { GraphQLServer } from './graphql-server';
8
8
  import { Schema } from './schema';
@@ -17,6 +17,7 @@ export declare type GraphQLConfig = {
17
17
  };
18
18
  export declare type GraphQLServerSlot = SlotRegistry<GraphQLServer>;
19
19
  export declare type SchemaSlot = SlotRegistry<Schema>;
20
+ export declare type PubSubSlot = SlotRegistry<PubSubEngine>;
20
21
  export declare type GraphQLServerOptions = {
21
22
  schemaSlot?: SchemaSlot;
22
23
  app?: Express;
@@ -38,15 +39,15 @@ export declare class GraphqlMain {
38
39
  * harmony context.
39
40
  */
40
41
  private context;
41
- /**
42
- * graphql pubsub. allows to emit events to clients.
43
- */
44
- readonly pubsub: PubSub;
45
42
  /**
46
43
  * logger extension.
47
44
  */
48
45
  readonly logger: Logger;
49
46
  private graphQLServerSlot;
47
+ /**
48
+ * graphql pubsub. allows to emit events to clients.
49
+ */
50
+ private pubSubSlot;
50
51
  constructor(
51
52
  /**
52
53
  * extension config
@@ -61,19 +62,24 @@ export declare class GraphqlMain {
61
62
  */
62
63
  context: Harmony,
63
64
  /**
64
- * graphql pubsub. allows to emit events to clients.
65
+ * logger extension.
65
66
  */
66
- pubsub: PubSub,
67
+ logger: Logger, graphQLServerSlot: GraphQLServerSlot,
67
68
  /**
68
- * logger extension.
69
+ * graphql pubsub. allows to emit events to clients.
69
70
  */
70
- logger: Logger, graphQLServerSlot: GraphQLServerSlot);
71
+ pubSubSlot: PubSubSlot);
72
+ get pubsub(): PubSubEngine;
71
73
  private modules;
72
74
  createServer(options: GraphQLServerOptions): Promise<Server>;
73
75
  /**
74
76
  * register a new graphql server.
75
77
  */
76
78
  registerServer(server: GraphQLServer): this;
79
+ /**
80
+ * register a pubsub client
81
+ */
82
+ registerPubSub(pubsub: PubSubEngine): this;
77
83
  /**
78
84
  * start a graphql server.
79
85
  */
@@ -90,7 +96,7 @@ export declare class GraphqlMain {
90
96
  private createRootModule;
91
97
  private buildModules;
92
98
  private getModuleDependencies;
93
- static slots: (((registerFn: () => string) => SlotRegistry<Schema>) | ((registerFn: () => string) => SlotRegistry<GraphQLServer>))[];
99
+ static slots: (((registerFn: () => string) => SlotRegistry<Schema>) | ((registerFn: () => string) => SlotRegistry<GraphQLServer>) | ((registerFn: () => string) => SlotRegistry<PubSubSlot>))[];
94
100
  static defaultConfig: {
95
101
  port: number;
96
102
  subscriptionsPortRange: number[];
@@ -98,5 +104,5 @@ export declare class GraphqlMain {
98
104
  };
99
105
  static runtime: import("@teambit/harmony").RuntimeDefinition;
100
106
  static dependencies: import("@teambit/harmony").Aspect[];
101
- static provider([loggerFactory]: [LoggerMain], config: GraphQLConfig, [moduleSlot, graphQLServerSlot]: [SchemaSlot, GraphQLServerSlot], context: Harmony): Promise<GraphqlMain>;
107
+ static provider([loggerFactory]: [LoggerMain], config: GraphQLConfig, [moduleSlot, graphQLServerSlot, pubSubSlot]: [SchemaSlot, GraphQLServerSlot, PubSubSlot], context: Harmony): Promise<GraphqlMain>;
102
108
  }
@@ -208,22 +208,28 @@ class GraphqlMain {
208
208
  */
209
209
  context,
210
210
  /**
211
- * graphql pubsub. allows to emit events to clients.
211
+ * logger extension.
212
212
  */
213
- pubsub,
213
+ logger, graphQLServerSlot,
214
214
  /**
215
- * logger extension.
215
+ * graphql pubsub. allows to emit events to clients.
216
216
  */
217
- logger, graphQLServerSlot) {
217
+ pubSubSlot) {
218
218
  this.config = config;
219
219
  this.moduleSlot = moduleSlot;
220
220
  this.context = context;
221
- this.pubsub = pubsub;
222
221
  this.logger = logger;
223
222
  this.graphQLServerSlot = graphQLServerSlot;
223
+ this.pubSubSlot = pubSubSlot;
224
224
  (0, _defineProperty2().default)(this, "modules", new Map());
225
225
  }
226
226
 
227
+ get pubsub() {
228
+ const pubSubSlots = this.pubSubSlot.values();
229
+ if (pubSubSlots.length) return pubSubSlots[0];
230
+ return new (_graphqlSubscriptions().PubSub)();
231
+ }
232
+
227
233
  async createServer(options) {
228
234
  const {
229
235
  graphiql = true
@@ -280,6 +286,17 @@ class GraphqlMain {
280
286
  this.graphQLServerSlot.register(server);
281
287
  return this;
282
288
  }
289
+ /**
290
+ * register a pubsub client
291
+ */
292
+
293
+
294
+ registerPubSub(pubsub) {
295
+ const pubSubSlots = this.pubSubSlot.toArray();
296
+ if (pubSubSlots.length) throw new Error('can not register more then one pubsub provider');
297
+ this.pubSubSlot.register(pubsub);
298
+ return this;
299
+ }
283
300
  /**
284
301
  * start a graphql server.
285
302
  */
@@ -404,15 +421,16 @@ class GraphqlMain {
404
421
  }).filter(module => !!module);
405
422
  }
406
423
 
407
- static async provider([loggerFactory], config, [moduleSlot, graphQLServerSlot], context) {
424
+ static async provider([loggerFactory], config, [moduleSlot, graphQLServerSlot, pubSubSlot], context) {
408
425
  const logger = loggerFactory.createLogger(_graphql2().GraphqlAspect.id);
409
- return new GraphqlMain(config, moduleSlot, context, new (_graphqlSubscriptions().PubSub)(), logger, graphQLServerSlot);
426
+ const graphqlMain = new GraphqlMain(config, moduleSlot, context, logger, graphQLServerSlot, pubSubSlot);
427
+ return graphqlMain;
410
428
  }
411
429
 
412
430
  }
413
431
 
414
432
  exports.GraphqlMain = GraphqlMain;
415
- (0, _defineProperty2().default)(GraphqlMain, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType()]);
433
+ (0, _defineProperty2().default)(GraphqlMain, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType()]);
416
434
  (0, _defineProperty2().default)(GraphqlMain, "defaultConfig", {
417
435
  port: 4000,
418
436
  subscriptionsPortRange: [2000, 2100],
@@ -1 +1 @@
1
- {"version":3,"sources":["graphql.main.runtime.ts"],"names":["Verb","GraphqlMain","constructor","config","moduleSlot","context","pubsub","logger","graphQLServerSlot","Map","createServer","options","graphiql","localSchema","createRootModule","schemaSlot","remoteSchemas","values","schemas","schema","concat","filter","x","app","use","origin","callback","credentials","request","res","params","customFormatErrorFn","err","error","Object","assign","ERR_CODE","originalError","errors","name","HTTP_CODE","code","rootValue","server","subscriptionsPort","subscriptionsPortRange","subscriptionServerPort","getPort","port","createSubscription","proxySubscription","registerServer","register","listen","serverPort","subServer","info","subscriptionsPath","range","from","to","Port","websocketServer","response","writeHead","end","debug","SubscriptionServer","execute","subscribe","onConnect","onWsConnect","path","proxServer","httpProxy","createProxyServer","on","req","socket","head","url","ws","target","host","modules","buildModules","GraphQLModule","imports","schemaSlots","toArray","map","extensionId","moduleDeps","getModuleDependencies","module","typeDefs","resolvers","session","verb","headers","READ","set","extension","extensions","get","Error","deps","getDependencies","ids","dep","id","Array","entries","depId","includes","undefined","provider","loggerFactory","createLogger","GraphqlAspect","PubSub","Slot","withType","MainRuntime","LoggerAspect","addRuntime"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AA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ACnB,CAACC,aAAD,CADmB,EAEnBlH,MAFmB,EAGnB,CAACC,UAAD,EAAaI,iBAAb,CAHmB,EAInBH,OAJmB,EAKnB;AACA,UAAME,MAAM,GAAG8G,aAAa,CAACC,YAAd,CAA2BC,0BAAcT,EAAzC,CAAf;AACA,WAAO,IAAI7G,WAAJ,CAAgBE,MAAhB,EAAwBC,UAAxB,EAAoCC,OAApC,EAA6C,KAAImH,8BAAJ,GAA7C,EAA2DjH,MAA3D,EAAmEC,iBAAnE,CAAP;AACD;;AA3OsB;;;gCAAZP,W,WAwNI,CAACwH,gBAAKC,QAAL,EAAD,EAA0BD,gBAAKC,QAAL,EAA1B,C;gCAxNJzH,W,mBA0NY;AACrB+C,EAAAA,IAAI,EAAE,IADe;AAErBH,EAAAA,sBAAsB,EAAE,CAAC,IAAD,EAAO,IAAP,CAFH;AAGrBY,EAAAA,iBAAiB,EAAE;AAHE,C;gCA1NZxD,W,aAgOM0H,kB;gCAhON1H,W,kBAiOW,CAAC2H,sBAAD,C;;AAaxBL,0BAAcM,UAAd,CAAyB5H,WAAzB","sourcesContent":["import { mergeSchemas } from 'graphql-tools';\nimport { GraphQLModule } from '@graphql-modules/core';\nimport { MainRuntime } from '@teambit/cli';\nimport { Harmony, Slot, SlotRegistry } from '@teambit/harmony';\nimport { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';\nimport express, { Express } from 'express';\nimport { graphqlHTTP } from 'express-graphql';\nimport { Port } from '@teambit/toolbox.network.get-port';\nimport { execute, subscribe } from 'graphql';\nimport { PubSub } from 'graphql-subscriptions';\nimport { createServer, Server } from 'http';\nimport httpProxy from 'http-proxy';\nimport { SubscriptionServer } from 'subscriptions-transport-ws';\nimport cors from 'cors';\nimport { GraphQLServer } from './graphql-server';\nimport { createRemoteSchemas } from './create-remote-schemas';\nimport { GraphqlAspect } from './graphql.aspect';\nimport { Schema } from './schema';\n\nexport enum Verb {\n WRITE = 'write',\n READ = 'read',\n}\n\nexport type GraphQLConfig = {\n port: number;\n subscriptionsPortRange: number[];\n subscriptionsPath: string;\n};\n\nexport type GraphQLServerSlot = SlotRegistry<GraphQLServer>;\n\nexport type SchemaSlot = SlotRegistry<Schema>;\n\nexport type GraphQLServerOptions = {\n schemaSlot?: SchemaSlot;\n app?: Express;\n graphiql?: boolean;\n remoteSchemas?: GraphQLServer[];\n subscriptionsPortRange?: number[];\n onWsConnect?: Function;\n};\n\nexport class GraphqlMain {\n constructor(\n /**\n * extension config\n */\n readonly config: GraphQLConfig,\n\n /**\n * slot for registering graphql modules\n */\n private moduleSlot: SchemaSlot,\n\n /**\n * harmony context.\n */\n private context: Harmony,\n\n /**\n * graphql pubsub. allows to emit events to clients.\n */\n readonly pubsub: PubSub,\n\n /**\n * logger extension.\n */\n readonly logger: Logger,\n\n private graphQLServerSlot: GraphQLServerSlot\n ) {}\n\n private modules = new Map<string, GraphQLModule>();\n\n async createServer(options: GraphQLServerOptions) {\n const { graphiql = true } = options;\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // TODO: @guy please consider to refactor to express extension.\n const app = options.app || express();\n app.use(\n // @ts-ignore todo: it's not clear what's the issue.\n cors({\n origin(origin, callback) {\n callback(null, true);\n },\n credentials: true,\n })\n );\n\n app.use(\n '/graphql',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n graphqlHTTP((request, res, params) => ({\n customFormatErrorFn: (err) => {\n this.logger.error('graphql got an error during running the following query:', params);\n this.logger.error('graphql error ', err);\n return Object.assign(err, {\n // @ts-ignore\n ERR_CODE: err?.originalError?.errors?.[0].ERR_CODE || err.originalError?.constructor?.name,\n // @ts-ignore\n HTTP_CODE: err?.originalError?.errors?.[0].HTTP_CODE || err.originalError?.code,\n });\n },\n schema,\n rootValue: request,\n graphiql,\n }))\n );\n\n const server = createServer(app);\n const subscriptionsPort = options.subscriptionsPortRange || this.config.subscriptionsPortRange;\n const subscriptionServerPort = await this.getPort(subscriptionsPort);\n const { port } = await this.createSubscription(options, subscriptionServerPort);\n this.proxySubscription(server, port);\n\n return server;\n }\n\n /**\n * register a new graphql server.\n */\n registerServer(server: GraphQLServer) {\n this.graphQLServerSlot.register(server);\n return this;\n }\n\n /**\n * start a graphql server.\n */\n async listen(port?: number, server?: Server, app?: Express) {\n const serverPort = port || this.config.port;\n const subServer = server || (await this.createServer({ app }));\n\n subServer.listen(serverPort, () => {\n this.logger.info(`API Server over HTTP is now running on http://localhost:${serverPort}`);\n this.logger.info(\n `API Server over web socket with subscriptions is now running on ws://localhost:${serverPort}/${this.config.subscriptionsPath}`\n );\n });\n }\n\n /**\n * register a new graphql module.\n */\n register(schema: Schema) {\n // const module = new GraphQLModule(schema);\n this.moduleSlot.register(schema);\n return this;\n }\n\n private async getPort(range: number[]) {\n const [from, to] = range;\n return Port.getPort(from, to);\n }\n\n /** create Subscription server with different port */\n\n private async createSubscription(options: GraphQLServerOptions, port: number) {\n // Create WebSocket listener server\n const websocketServer = createServer((request, response) => {\n response.writeHead(404);\n response.end();\n });\n\n // Bind it to port and start listening\n websocketServer.listen(port, () =>\n this.logger.debug(`Websocket Server is now running on http://localhost:${port}`)\n );\n\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const subServer = new SubscriptionServer(\n {\n execute,\n subscribe,\n schema,\n onConnect: options.onWsConnect,\n },\n {\n server: websocketServer,\n path: this.config.subscriptionsPath,\n }\n );\n return { subServer, port };\n }\n /** proxy ws Subscription server to avoid conflict with different websocket connections */\n\n private proxySubscription(server: Server, port: number) {\n const proxServer = httpProxy.createProxyServer();\n const subscriptionsPath = this.config.subscriptionsPath;\n const logger = this.logger;\n server.on('upgrade', function (req, socket, head) {\n if (req.url === subscriptionsPath) {\n logger.debug(`proxy from ${req.url} to ${port}`);\n proxServer.ws(req, socket, head, { target: { host: 'localhost', port } });\n }\n });\n }\n\n private createRootModule(schemaSlot?: SchemaSlot) {\n const modules = this.buildModules(schemaSlot);\n\n return new GraphQLModule({\n imports: modules,\n });\n }\n\n private buildModules(schemaSlot?: SchemaSlot) {\n const schemaSlots = schemaSlot ? schemaSlot.toArray() : this.moduleSlot.toArray();\n return schemaSlots.map(([extensionId, schema]) => {\n const moduleDeps = this.getModuleDependencies(extensionId);\n\n const module = new GraphQLModule({\n typeDefs: schema.typeDefs,\n resolvers: schema.resolvers,\n imports: moduleDeps,\n context: (session) => {\n return {\n ...session,\n verb: session?.headers?.['x-verb'] || Verb.READ,\n };\n },\n });\n\n this.modules.set(extensionId, module);\n\n return module;\n });\n }\n\n private getModuleDependencies(extensionId: string): GraphQLModule[] {\n const extension = this.context.extensions.get(extensionId);\n if (!extension) throw new Error(`aspect ${extensionId} was not found`);\n const deps = this.context.getDependencies(extension);\n const ids = deps.map((dep) => dep.id);\n\n // @ts-ignore check :TODO why types are breaking here.\n return Array.from(this.modules.entries())\n .map(([depId, module]) => {\n const dep = ids.includes(depId);\n if (!dep) return undefined;\n return module;\n })\n .filter((module) => !!module);\n }\n\n static slots = [Slot.withType<Schema>(), Slot.withType<GraphQLServer>()];\n\n static defaultConfig = {\n port: 4000,\n subscriptionsPortRange: [2000, 2100],\n subscriptionsPath: '/subscriptions',\n };\n\n static runtime = MainRuntime;\n static dependencies = [LoggerAspect];\n\n static async provider(\n [loggerFactory]: [LoggerMain],\n config: GraphQLConfig,\n [moduleSlot, graphQLServerSlot]: [SchemaSlot, GraphQLServerSlot],\n context: Harmony\n ) {\n const logger = loggerFactory.createLogger(GraphqlAspect.id);\n return new GraphqlMain(config, moduleSlot, context, new PubSub(), logger, graphQLServerSlot);\n }\n}\n\nGraphqlAspect.addRuntime(GraphqlMain);\n"]}
1
+ {"version":3,"sources":["graphql.main.runtime.ts"],"names":["Verb","GraphqlMain","constructor","config","moduleSlot","context","logger","graphQLServerSlot","pubSubSlot","Map","pubsub","pubSubSlots","values","length","PubSub","createServer","options","graphiql","localSchema","createRootModule","schemaSlot","remoteSchemas","schemas","schema","concat","filter","x","app","use","origin","callback","credentials","request","res","params","customFormatErrorFn","err","error","Object","assign","ERR_CODE","originalError","errors","name","HTTP_CODE","code","rootValue","server","subscriptionsPort","subscriptionsPortRange","subscriptionServerPort","getPort","port","createSubscription","proxySubscription","registerServer","register","registerPubSub","toArray","Error","listen","serverPort","subServer","info","subscriptionsPath","range","from","to","Port","websocketServer","response","writeHead","end","debug","SubscriptionServer","execute","subscribe","onConnect","onWsConnect","path","proxServer","httpProxy","createProxyServer","on","req","socket","head","url","ws","target","host","modules","buildModules","GraphQLModule","imports","schemaSlots","map","extensionId","moduleDeps","getModuleDependencies","module","typeDefs","resolvers","session","verb","headers","READ","set","extension","extensions","get","deps","getDependencies","ids","dep","id","Array","entries","depId","includes","undefined","provider","loggerFactory","createLogger","GraphqlAspect","graphqlMain","Slot","withType","MainRuntime","LoggerAspect","addRuntime"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAA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,WAAzB","sourcesContent":["import { mergeSchemas } from 'graphql-tools';\nimport { GraphQLModule } from '@graphql-modules/core';\nimport { MainRuntime } from '@teambit/cli';\nimport { Harmony, Slot, SlotRegistry } from '@teambit/harmony';\nimport { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';\nimport express, { Express } from 'express';\nimport { graphqlHTTP } from 'express-graphql';\nimport { Port } from '@teambit/toolbox.network.get-port';\nimport { execute, subscribe } from 'graphql';\nimport { PubSubEngine, PubSub } from 'graphql-subscriptions';\nimport { createServer, Server } from 'http';\nimport httpProxy from 'http-proxy';\nimport { SubscriptionServer } from 'subscriptions-transport-ws';\nimport cors from 'cors';\nimport { GraphQLServer } from './graphql-server';\nimport { createRemoteSchemas } from './create-remote-schemas';\nimport { GraphqlAspect } from './graphql.aspect';\nimport { Schema } from './schema';\n\nexport enum Verb {\n WRITE = 'write',\n READ = 'read',\n}\n\nexport type GraphQLConfig = {\n port: number;\n subscriptionsPortRange: number[];\n subscriptionsPath: string;\n};\n\nexport type GraphQLServerSlot = SlotRegistry<GraphQLServer>;\n\nexport type SchemaSlot = SlotRegistry<Schema>;\n\nexport type PubSubSlot = SlotRegistry<PubSubEngine>;\n\nexport type GraphQLServerOptions = {\n schemaSlot?: SchemaSlot;\n app?: Express;\n graphiql?: boolean;\n remoteSchemas?: GraphQLServer[];\n subscriptionsPortRange?: number[];\n onWsConnect?: Function;\n};\n\nexport class GraphqlMain {\n constructor(\n /**\n * extension config\n */\n readonly config: GraphQLConfig,\n\n /**\n * slot for registering graphql modules\n */\n private moduleSlot: SchemaSlot,\n\n /**\n * harmony context.\n */\n private context: Harmony,\n\n /**\n * logger extension.\n */\n readonly logger: Logger,\n\n private graphQLServerSlot: GraphQLServerSlot,\n\n /**\n * graphql pubsub. allows to emit events to clients.\n */\n private pubSubSlot: PubSubSlot\n ) {}\n\n get pubsub(): PubSubEngine {\n const pubSubSlots = this.pubSubSlot.values();\n if (pubSubSlots.length) return pubSubSlots[0];\n return new PubSub();\n }\n\n private modules = new Map<string, GraphQLModule>();\n\n async createServer(options: GraphQLServerOptions) {\n const { graphiql = true } = options;\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // TODO: @guy please consider to refactor to express extension.\n const app = options.app || express();\n app.use(\n // @ts-ignore todo: it's not clear what's the issue.\n cors({\n origin(origin, callback) {\n callback(null, true);\n },\n credentials: true,\n })\n );\n\n app.use(\n '/graphql',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n graphqlHTTP((request, res, params) => ({\n customFormatErrorFn: (err) => {\n this.logger.error('graphql got an error during running the following query:', params);\n this.logger.error('graphql error ', err);\n return Object.assign(err, {\n // @ts-ignore\n ERR_CODE: err?.originalError?.errors?.[0].ERR_CODE || err.originalError?.constructor?.name,\n // @ts-ignore\n HTTP_CODE: err?.originalError?.errors?.[0].HTTP_CODE || err.originalError?.code,\n });\n },\n schema,\n rootValue: request,\n graphiql,\n }))\n );\n\n const server = createServer(app);\n const subscriptionsPort = options.subscriptionsPortRange || this.config.subscriptionsPortRange;\n const subscriptionServerPort = await this.getPort(subscriptionsPort);\n const { port } = await this.createSubscription(options, subscriptionServerPort);\n this.proxySubscription(server, port);\n\n return server;\n }\n\n /**\n * register a new graphql server.\n */\n registerServer(server: GraphQLServer) {\n this.graphQLServerSlot.register(server);\n return this;\n }\n\n /**\n * register a pubsub client\n */\n registerPubSub(pubsub: PubSubEngine) {\n const pubSubSlots = this.pubSubSlot.toArray();\n if (pubSubSlots.length) throw new Error('can not register more then one pubsub provider');\n this.pubSubSlot.register(pubsub);\n return this;\n }\n\n /**\n * start a graphql server.\n */\n async listen(port?: number, server?: Server, app?: Express) {\n const serverPort = port || this.config.port;\n const subServer = server || (await this.createServer({ app }));\n\n subServer.listen(serverPort, () => {\n this.logger.info(`API Server over HTTP is now running on http://localhost:${serverPort}`);\n this.logger.info(\n `API Server over web socket with subscriptions is now running on ws://localhost:${serverPort}/${this.config.subscriptionsPath}`\n );\n });\n }\n\n /**\n * register a new graphql module.\n */\n register(schema: Schema) {\n // const module = new GraphQLModule(schema);\n this.moduleSlot.register(schema);\n return this;\n }\n\n private async getPort(range: number[]) {\n const [from, to] = range;\n return Port.getPort(from, to);\n }\n\n /** create Subscription server with different port */\n\n private async createSubscription(options: GraphQLServerOptions, port: number) {\n // Create WebSocket listener server\n const websocketServer = createServer((request, response) => {\n response.writeHead(404);\n response.end();\n });\n\n // Bind it to port and start listening\n websocketServer.listen(port, () =>\n this.logger.debug(`Websocket Server is now running on http://localhost:${port}`)\n );\n\n const localSchema = this.createRootModule(options.schemaSlot);\n const remoteSchemas = await createRemoteSchemas(options.remoteSchemas || this.graphQLServerSlot.values());\n const schemas = [localSchema.schema].concat(remoteSchemas).filter((x) => x);\n const schema = mergeSchemas({\n schemas,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const subServer = new SubscriptionServer(\n {\n execute,\n subscribe,\n schema,\n onConnect: options.onWsConnect,\n },\n {\n server: websocketServer,\n path: this.config.subscriptionsPath,\n }\n );\n return { subServer, port };\n }\n /** proxy ws Subscription server to avoid conflict with different websocket connections */\n\n private proxySubscription(server: Server, port: number) {\n const proxServer = httpProxy.createProxyServer();\n const subscriptionsPath = this.config.subscriptionsPath;\n const logger = this.logger;\n server.on('upgrade', function (req, socket, head) {\n if (req.url === subscriptionsPath) {\n logger.debug(`proxy from ${req.url} to ${port}`);\n proxServer.ws(req, socket, head, { target: { host: 'localhost', port } });\n }\n });\n }\n\n private createRootModule(schemaSlot?: SchemaSlot) {\n const modules = this.buildModules(schemaSlot);\n\n return new GraphQLModule({\n imports: modules,\n });\n }\n\n private buildModules(schemaSlot?: SchemaSlot) {\n const schemaSlots = schemaSlot ? schemaSlot.toArray() : this.moduleSlot.toArray();\n return schemaSlots.map(([extensionId, schema]) => {\n const moduleDeps = this.getModuleDependencies(extensionId);\n\n const module = new GraphQLModule({\n typeDefs: schema.typeDefs,\n resolvers: schema.resolvers,\n imports: moduleDeps,\n context: (session) => {\n return {\n ...session,\n verb: session?.headers?.['x-verb'] || Verb.READ,\n };\n },\n });\n\n this.modules.set(extensionId, module);\n\n return module;\n });\n }\n\n private getModuleDependencies(extensionId: string): GraphQLModule[] {\n const extension = this.context.extensions.get(extensionId);\n if (!extension) throw new Error(`aspect ${extensionId} was not found`);\n const deps = this.context.getDependencies(extension);\n const ids = deps.map((dep) => dep.id);\n\n // @ts-ignore check :TODO why types are breaking here.\n return Array.from(this.modules.entries())\n .map(([depId, module]) => {\n const dep = ids.includes(depId);\n if (!dep) return undefined;\n return module;\n })\n .filter((module) => !!module);\n }\n\n static slots = [Slot.withType<Schema>(), Slot.withType<GraphQLServer>(), Slot.withType<PubSubSlot>()];\n\n static defaultConfig = {\n port: 4000,\n subscriptionsPortRange: [2000, 2100],\n subscriptionsPath: '/subscriptions',\n };\n\n static runtime = MainRuntime;\n static dependencies = [LoggerAspect];\n\n static async provider(\n [loggerFactory]: [LoggerMain],\n config: GraphQLConfig,\n [moduleSlot, graphQLServerSlot, pubSubSlot]: [SchemaSlot, GraphQLServerSlot, PubSubSlot],\n context: Harmony\n ) {\n const logger = loggerFactory.createLogger(GraphqlAspect.id);\n const graphqlMain = new GraphqlMain(config, moduleSlot, context, logger, graphQLServerSlot, pubSubSlot);\n return graphqlMain;\n }\n}\n\nGraphqlAspect.addRuntime(GraphqlMain);\n"]}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/graphql",
3
- "version": "0.0.574",
3
+ "version": "0.0.578",
4
4
  "homepage": "https://bit.dev/teambit/harmony/graphql",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.harmony",
8
8
  "name": "graphql",
9
- "version": "0.0.574"
9
+ "version": "0.0.578"
10
10
  },
11
11
  "dependencies": {
12
12
  "@teambit/harmony": "0.2.11",
@@ -32,12 +32,12 @@
32
32
  "bufferutil": "4.0.3",
33
33
  "@babel/runtime": "7.12.18",
34
34
  "core-js": "^3.0.0",
35
- "@teambit/cli": "0.0.397",
36
- "@teambit/logger": "0.0.485",
37
- "@teambit/toolbox.network.get-port": "0.0.101",
38
- "@teambit/preview": "0.0.574",
39
- "@teambit/ui": "0.0.574",
40
- "@teambit/ui-foundation.ui.is-browser": "0.0.474"
35
+ "@teambit/cli": "0.0.399",
36
+ "@teambit/logger": "0.0.487",
37
+ "@teambit/toolbox.network.get-port": "0.0.103",
38
+ "@teambit/preview": "0.0.578",
39
+ "@teambit/ui": "0.0.578",
40
+ "@teambit/ui-foundation.ui.is-browser": "0.0.476"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/cors": "2.8.10",
@@ -54,7 +54,7 @@
54
54
  "peerDependencies": {
55
55
  "@apollo/client": "^3.0.0",
56
56
  "graphql": "14.7.0",
57
- "@teambit/legacy": "1.0.183",
57
+ "@teambit/legacy": "1.0.185",
58
58
  "react-dom": "^16.8.0 || ^17.0.0",
59
59
  "react": "^16.8.0 || ^17.0.0"
60
60
  },
@@ -84,7 +84,7 @@
84
84
  "react": "-"
85
85
  },
86
86
  "peerDependencies": {
87
- "@teambit/legacy": "1.0.183",
87
+ "@teambit/legacy": "1.0.185",
88
88
  "react-dom": "^16.8.0 || ^17.0.0",
89
89
  "react": "^16.8.0 || ^17.0.0"
90
90
  }