Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgdate to latest Apollo server / subscriptions #118

Open
wants to merge 28 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ coverage/
npm-debug.log
stats.json
yarn-error.log
*.lock
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,43 @@
<a name="0.3.7.4"></a>
# 0.3.7.4 (2023-01-22)

- Upgrade to Apollo server v4
- According to v4, moleculerApollo handler disabled and moleculerMiddleware is used instead


<a name="0.3.7.3"></a>
# 0.3.7.3 (2022-11-08)

[#118](https://github.com/moleculerjs/moleculer-apollo-server/pull/118)

## Changes
- Original Package.json description
- Removed extra code from examples
- Comments cleanup

<a name="0.3.7.2"></a>
# 0.3.7.2 (2022-10-23)

## Changes
- remove createPubSub from subscriptoins:{},will be overriden in methods of host service
- change prepareContextParams, last 2 params - args, "root" added
- binds any functions in serverOptions to service

<a name="0.3.7.1"></a>
# 0.3.7.1 (2022-10-20)

## Changes
- upgrade to Apollo server v3 ( + switch from subscriptions-transport-ws to graphql-ws )
- add Custom PubSub creator ( for use custom PubSubEngine )
- add Update/Reload schema without restarting server/ws
- Playground ( RenderPageOptions ) options in serverOptions.playgroundOptions
- add serverOptions.subscriptions.onConnect should return acts lile graphql-ws
- add serverOptions.subscriptions.context should return user account ( like "authenticate" method )
- CAUTION: with new graphql-ws subscriptions are not available in build-in playground
- WARNING: graphql-upload disabled ( new versions is mjs type )
- Not tested - DataLoader
- Example in examples/full/
--------------------------------------------------
<a name="0.3.7"></a>
# 0.3.7 (2022-10-04)

Expand Down
2 changes: 1 addition & 1 deletion examples/full/generated-schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ enum UserType {
ADMIN
PUBLISHER
READER
}
}
74 changes: 71 additions & 3 deletions examples/full/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ const { Kind } = require("graphql");
const { ServiceBroker } = require("moleculer");
const ApiGateway = require("moleculer-web");
const { ApolloService } = require("../../index");
const { PubSub } = require("graphql-subscriptions");

const broker = new ServiceBroker({
logLevel: process.env.LOGLEVEL || "info" /*, transporter: "NATS"*/,
hotReload: true,
});

broker.createService({
Expand Down Expand Up @@ -59,25 +61,91 @@ broker.createService({
// API Gateway route options
routeOptions: {
path: "/graphql",
cors: true,
cors: {
origin: ["http://localhost:3001", "http://localhost:3000"],
credentials: true,
// Configures the Access-Control-Allow-Methods CORS header.
methods: ["GET", "OPTIONS", "POST", "PUT", "DELETE"],
},
mappingPolicy: "restrict",
authentication: "graphql_authenticate",
authorization: "graphql_authorize",
},

// https://www.apollographql.com/docs/apollo-server/v2/api/apollo-server.html
serverOptions: {
tracing: false,
tracing: true,

playgroundOptions: {
settings: {
"editor.theme": "dark",
},
},

engine: {
apiKey: process.env.APOLLO_ENGINE_KEY,
},

subscriptions: {
async onConnect($ctx) {
const {
params: {
connectionParams,
extra: { request },
},
} = $ctx;
return true;
},
async context($ctx) {
const {
params: {
connectionParams,
extra: { request },
},
} = $ctx;
// will be set to ctx.meta.user ( for subsciption filters )
return this.graphql_authenticate($ctx, undefined, request)
.then(user => {
return user;
})
.catch(e => null);
},
},
},
}),
],

settings: {
path: "/",
cors: {
origin: ["http://localhost:3000"],
credentials: true,
// Configures the Access-Control-Allow-Methods CORS header.
methods: ["GET", "OPTIONS", "POST", "PUT", "DELETE"],
},
port: 3000,
},

actions: {},

methods: {
createPubSub() {
return new PubSub();
},
prepareContextParams(mergedParams, actionName, context, args, root) {
return mergedParams;
},

async graphql_authenticate(ctx, route, req, res) {
return this.Promise.resolve({ username: "john", email: "[email protected]" });
},
async graphql_authorize(ctx, route, req, res) {},
},

events: {
"graphql.schema.updated"({ schema }) {
fs.writeFileSync(__dirname + "/generated-schema.gql", schema, "utf8");
this.logger.info("Generated GraphQL schema:\n\n" + schema);
// this.logger.info("Generated GraphQL schema:\n\n" + schema);
},
},
});
Expand Down
9 changes: 5 additions & 4 deletions examples/simple/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { MoleculerClientError } = require("moleculer").Errors;
const ApiGateway = require("moleculer-web");
const { ApolloService } = require("../../index");

const broker = new ServiceBroker({ logLevel: "info", hotReload: true });
const broker = new ServiceBroker({ logLevel: "debug", hotReload: true });

broker.createService({
name: "api",
Expand Down Expand Up @@ -47,7 +47,7 @@ broker.createService({
query: "hello: String!",
},
handler() {
return "Hello Moleculer!";
return "Hello Moleculer! 2";
},
},
welcome: {
Expand Down Expand Up @@ -104,8 +104,9 @@ broker.createService({
});

broker.start().then(async () => {
broker.repl();
// broker.repl();

/*
const res = await broker.call("api.graphql", {
query: "query { hello }",
});
Expand All @@ -120,7 +121,7 @@ broker.start().then(async () => {
if (res.errors && res.errors.length > 0) return res.errors.forEach(broker.logger.error);

broker.logger.info(res.data);

*/
broker.logger.info("----------------------------------------------------------");
broker.logger.info("Open the http://localhost:3000/graphql URL in your browser");
broker.logger.info("----------------------------------------------------------");
Expand Down
24 changes: 20 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { PubSubEngine } from "graphql-subscriptions";
import { ServerOptions } from "graphql-ws";

declare module "moleculer-apollo-server" {
import { ServiceSchema, Context } from "moleculer";
import { Config } from "apollo-server-core";
import { OptionsUrlencoded } from "body-parser";
import { SchemaDirectiveVisitor, IResolvers } from "graphql-tools";

import { RenderPageOptions } from "@apollographql/graphql-playground-html";
export {
GraphQLExtension,
gql,
Expand All @@ -17,9 +20,10 @@ declare module "moleculer-apollo-server" {
defaultPlaygroundOptions,
} from "apollo-server-core";

export { GraphQLUpload } from "graphql-upload";

// export { GraphQLUpload } from "graphql-upload";

export * from "graphql-tools";
// export * from "graphql-tools";

export interface ApolloServerOptions {
path: string;
Expand Down Expand Up @@ -86,6 +90,18 @@ declare module "moleculer-apollo-server" {
onBeforeCall?: (ctx: Context, route: any, req: any, res: any) => Promise<any>;
onAfterCall?: (ctx: Context, route: any, req: any, res: any, data: any) => Promise<any>;
}
// Promise<GraphQLExecutionContextValue> | GraphQLExecutionContextValue)

export interface SubscriptionsConfig {
onConnect?:(ctx: Context) => Promise<Record<string, unknown> | boolean | void> | Record<string, unknown> | boolean | void;
context?:(ctx:Context) => Promise<any>;
createPubSub?:() => typeof PubSubEngine;
}

export interface ServerMixinOptions extends Config {
playgroundOptions?:RenderPageOptions;
subscriptions?:SubscriptionsConfig;
}

export interface ApolloServiceOptions {
typeDefs?: string | string[];
Expand All @@ -94,7 +110,7 @@ declare module "moleculer-apollo-server" {
[name: string]: typeof SchemaDirectiveVisitor;
};
routeOptions?: ServiceRouteOptions;
serverOptions?: Config;
serverOptions?: ServerMixinOptions;
checkActionVisibility?: boolean;
autoUpdateSchema?: boolean;
}
Expand Down
15 changes: 9 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@

"use strict";

const core = require("apollo-server-core");
const { GraphQLUpload } = require("graphql-upload");
const { GraphQLError } = require("graphql");

// const GraphQLUpload = require("graphql-upload");
const { ApolloServer } = require("./src/ApolloServer");
const ApolloService = require("./src/service");
const gql = require("./src/gql");

module.exports = {
// Only GraphQLError exposes, other errors need custom creation
GraphQLError,
// Core
// Next defs are removed in v4 from core
/*
GraphQLExtension: core.GraphQLExtension,
gql: core.gql,
ApolloError: core.ApolloError,
Expand All @@ -32,12 +37,10 @@ module.exports = {
ForbiddenError: core.ForbiddenError,
UserInputError: core.UserInputError,
defaultPlaygroundOptions: core.defaultPlaygroundOptions,

// GraphQL tools
...require("graphql-tools"),
*/

// GraphQL Upload
GraphQLUpload,
// GraphQLUpload,

// Apollo Server
ApolloServer,
Expand Down
Loading