Skip to content

Commit

Permalink
feat(apollo): update drivers, remove deprecated options, fix runners
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Feb 7, 2023
1 parent d97e653 commit 1e099fa
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 109 deletions.
95 changes: 45 additions & 50 deletions packages/apollo/lib/drivers/apollo-base.driver.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import { ApolloServer, type BaseContext } from '@apollo/server';
import { ApolloServerPluginLandingPageGraphQLPlayground } from '@apollo/server-plugin-landing-page-graphql-playground';
import { ApolloServerErrorCode } from '@apollo/server/errors';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginLandingPageDisabled } from '@apollo/server/plugin/disabled';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { HttpStatus } from '@nestjs/common';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { isFunction } from '@nestjs/common/utils/shared.utils';
import { AbstractGraphQLDriver } from '@nestjs/graphql';

import { GraphQLError, GraphQLFormattedError } from 'graphql';
import * as omit from 'lodash.omit';
import { ApolloDriverConfig } from '../interfaces';
import { createAsyncIterator } from '../utils/async-iterator.util';

import { ApolloServer, type BaseContext } from '@apollo/server';
import { ApolloServerErrorCode } from '@apollo/server/errors';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
import * as express from 'express';
import * as http from 'node:http';

import { fastifyApolloHandler } from '@as-integrations/fastify';
import { HttpStatus } from '@nestjs/common';

const apolloPredefinedExceptions: Partial<Record<HttpStatus, string>> = {
[HttpStatus.BAD_REQUEST]: ApolloServerErrorCode.BAD_USER_INPUT,
[HttpStatus.UNAUTHORIZED]: 'UNAUTHENTICATED',
Expand Down Expand Up @@ -65,7 +61,9 @@ export abstract class ApolloBaseDriver<
typeof options.playground === 'object' ? options.playground : undefined;
defaults = {
...defaults,
plugins: [ApolloServerPluginLandingPageLocalDefault(playgroundOptions)],
plugins: [
ApolloServerPluginLandingPageGraphQLPlayground(playgroundOptions),
],
};
} else if (
(options.playground === undefined &&
Expand All @@ -74,7 +72,7 @@ export abstract class ApolloBaseDriver<
) {
defaults = {
...defaults,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
plugins: [ApolloServerPluginLandingPageDisabled()],
};
}

Expand Down Expand Up @@ -109,66 +107,63 @@ export abstract class ApolloBaseDriver<
);
}

protected async registerExpress(options: T, hooks?: any) {
if (hooks?.preStartHook) {
hooks?.preStartHook();
}

const cors = loadPackage('cors', null, () => require('cors'));

protected async registerExpress(
options: T,
{ preStartHook }: { preStartHook?: () => void } = {},
) {
const { path, typeDefs, resolvers, schema } = options;

const httpAdapter = this.httpAdapterHost.httpAdapter;
const app = httpAdapter.getInstance();
const httpServer = http.createServer(app);
const drainHttpServerPlugin = ApolloServerPluginDrainHttpServer({
httpServer: httpAdapter.getHttpServer(),
});

preStartHook?.();

// Set up Apollo Server
const server = new ApolloServer({
typeDefs,
resolvers,
schema,
...options,
/**
* @TODO
* should remove serverWillStart from default plugins.
* after include plugins here
*/
// TODO: fix - dont override plugins
// plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
plugins: options.plugins
? options.plugins.concat([drainHttpServerPlugin])
: [drainHttpServerPlugin],
});

await server.start();

app.use(
path,
cors(options.cors),
express.json(),
expressMiddleware(server),
);
app.use(path, expressMiddleware(server));

this.apolloServer = server;
}

protected async registerFastify(options: T, hooks?: any) {
if (hooks?.preStartHook) {
hooks?.preStartHook();
}

const cors = loadPackage('@fastify/cors', null, () =>
require('@fastify/cors'),
protected async registerFastify(
options: T,
{ preStartHook }: { preStartHook?: () => void } = {},
) {
const { fastifyApolloDrainPlugin, fastifyApolloHandler } = loadPackage(
'@as-integrations/fastify',
'GraphQLModule',
() => require('@as-integrations/fastify'),
);

const httpAdapter = this.httpAdapterHost.httpAdapter;
const app = httpAdapter.getInstance();

const { path, typeDefs, resolvers, schema } = options;
const apolloDrainPlugin = fastifyApolloDrainPlugin(app);

preStartHook?.();

const server = new ApolloServer<BaseContext>({
typeDefs,
resolvers,
schema,
...options,
// TODO: fix - dont override plugin
//plugins: [fastifyApolloDrainPlugin(app)],
plugins: options.plugins
? options.plugins.concat([apolloDrainPlugin])
: [apolloDrainPlugin],
});

await server.start();
Expand All @@ -179,8 +174,6 @@ export abstract class ApolloBaseDriver<
handler: fastifyApolloHandler(server),
});

await app.register(cors, options.cors);

this.apolloServer = server;
}

Expand Down Expand Up @@ -219,13 +212,15 @@ export abstract class ApolloBaseDriver<
},
});
} else {
error = new GraphQLError(exceptionRef.message, httpStatus?.toString());
error = new GraphQLError(exceptionRef.message, {
extensions: {
code: ApolloServerErrorCode.INTERNAL_SERVER_ERROR,
status: httpStatus,
},
});
}

error.stack = exceptionRef?.stacktrace;
//TODO: we need to verify if previous behavior is to be kept
// if so we must open a PR on Apollo to include response inside the raised exception
//https://github.com/apollographql/apollo-server/blob/e6d0d6d9cbd78d4914adf2abb04d84710991849a/packages/server/src/errorNormalize.ts#L58
error.extensions['response'] = exceptionRef?.response;
return error;
};
Expand Down
9 changes: 0 additions & 9 deletions packages/apollo/lib/drivers/apollo-federation.driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ export class ApolloFederationDriver extends ApolloBaseDriver {
const adapterOptions = await this.graphqlFederationFactory.mergeWithSchema(
options,
);
await this.runExecutorFactoryIfPresent(adapterOptions);

if (options.definitions && options.definitions.path) {
const { printSubgraphSchema } = loadPackage(
Expand All @@ -50,12 +49,4 @@ export class ApolloFederationDriver extends ApolloBaseDriver {
);
}
}

private async runExecutorFactoryIfPresent(apolloOptions: ApolloDriverConfig) {
if (!apolloOptions.executorFactory) {
return;
}
const executor = await apolloOptions.executorFactory(apolloOptions.schema);
apolloOptions.executor = executor;
}
}
40 changes: 8 additions & 32 deletions packages/apollo/lib/interfaces/apollo-driver-config.interface.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,26 @@
import { ApolloServerOptionsWithTypeDefs } from '@apollo/server';
import { ApolloServerPluginLandingPageGraphQLPlaygroundOptions } from '@apollo/server-plugin-landing-page-graphql-playground';
import {
GqlModuleAsyncOptions,
GqlModuleOptions,
GqlOptionsFactory,
SubscriptionConfig,
} from '@nestjs/graphql';
import { GraphQLSchema } from 'graphql';
import { CorsOptions } from 'cors';

export interface ServerRegistration {
/**
* Path to mount GraphQL API
*/
path?: string;

/**
* CORS configuration
*/
cors?: CorsOptions;

/**
* Body-parser configuration
*/
bodyParserConfig?: any | boolean;

/**
* On health check hook
*/
onHealthCheck?: (req: any) => Promise<any>;

/**
* Whether to enable health check
*/
disableHealthCheck?: boolean;
}

export interface ApolloDriverConfig
extends Omit</*Config*/ any, 'typeDefs'>,
extends Omit<
ApolloServerOptionsWithTypeDefs<any>,
'typeDefs' | 'schema' | 'resolvers' | 'gateway'
>,
ServerRegistration,
Omit<GqlModuleOptions, 'context'> {
/**
* Executor factory function
*/
executorFactory?: (
schema: GraphQLSchema,
) => /*GraphQLExecutor | Promise<GraphQLExecutor>*/ any;

GqlModuleOptions {
/**
* If enabled, "subscriptions-transport-ws" will be automatically registered.
*/
Expand All @@ -58,7 +34,7 @@ export interface ApolloDriverConfig
/**
* GraphQL playground options.
*/
playground?: boolean;
playground?: boolean | ApolloServerPluginLandingPageGraphQLPlaygroundOptions;

/**
* If enabled, will register a global interceptor that automatically maps
Expand Down
7 changes: 1 addition & 6 deletions packages/apollo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
},
"dependencies": {
"@apollo/server": "4.3.2",
"@apollo/server-plugin-landing-page-graphql-playground": "4.0.0",
"iterall": "1.3.0",
"lodash.omit": "4.5.0",
"tslib": "2.5.0"
Expand All @@ -56,12 +57,6 @@
},
"@as-integrations/fastify": {
"optional": true
},
"@fastify/cors": {
"optional": true
},
"cors": {
"optional": true
}
}
}
9 changes: 0 additions & 9 deletions packages/graphql/lib/exceptions/graphql-exception.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/graphql/lib/exceptions/index.ts

This file was deleted.

3 changes: 1 addition & 2 deletions packages/graphql/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ export * from './graphql-ast.explorer';
export * from './graphql-definitions.factory';
export * from './graphql-schema.host';
export * from './graphql-types.loader';
export * from './graphql.constants';
export * from './graphql.factory';
export * from './graphql.module';
export * from './graphql.constants';
export * from './interfaces';
export * from './scalars';
export * from './schema-builder';
Expand All @@ -20,4 +20,3 @@ export * from './type-factories';
export * from './type-helpers';
export * from './utils/extend.util';
export * from './utils/transform-schema.util';
export * from './exceptions';
32 changes: 32 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@
"@apollo/utils.keyvaluecache" "^2.1.0"
"@apollo/utils.logger" "^2.0.0"

"@apollo/[email protected]":
version "4.0.0"
resolved "https://registry.yarnpkg.com/@apollo/server-plugin-landing-page-graphql-playground/-/server-plugin-landing-page-graphql-playground-4.0.0.tgz#eff593de6c37a0b63d740f1c6498d69f67644aed"
integrity sha512-PBDtKI/chJ+hHeoJUUH9Kuqu58txQl00vUGuxqiC9XcReulIg7RjsyD0G1u3drX4V709bxkL5S0nTeXfRHD0qA==
dependencies:
"@apollographql/graphql-playground-html" "1.6.29"

"@apollo/[email protected]":
version "4.1.0"
resolved "https://registry.yarnpkg.com/@apollo/server-plugin-response-cache/-/server-plugin-response-cache-4.1.0.tgz#2c6752bec3bb14d2901688ae631220fd37b938a2"
Expand Down Expand Up @@ -283,6 +290,13 @@
resolved "https://registry.yarnpkg.com/@apollo/utils.withrequired/-/utils.withrequired-2.0.0.tgz#f39340f7b621b214d7a063b8da3eab24a9b7b7e8"
integrity sha512-+djpTu6AEE/A1etryZs9tmXRyDY6XXGe3G29MS/LB09uHq3pcl3n4Q5lvDTL5JWKuJixrulg5djePLDAooG8dQ==

"@apollographql/[email protected]":
version "1.6.29"
resolved "https://registry.yarnpkg.com/@apollographql/graphql-playground-html/-/graphql-playground-html-1.6.29.tgz#a7a646614a255f62e10dcf64a7f68ead41dec453"
integrity sha512-xCcXpoz52rI4ksJSdOCxeOCn2DLocxwHf9dVT/Q90Pte1LX+LY+91SFtJF3KXVHH8kEin+g1KKCQPKBjZJfWNA==
dependencies:
xss "^1.0.8"

"@as-integrations/[email protected]":
version "1.3.0"
resolved "https://registry.yarnpkg.com/@as-integrations/fastify/-/fastify-1.3.0.tgz#fc987fffabc8f34ee301eb66f2a7da2e63621004"
Expand Down Expand Up @@ -3941,6 +3955,11 @@ combined-stream@^1.0.8:
dependencies:
delayed-stream "~1.0.0"

commander@^2.20.3:
version "2.20.3"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"
integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==

commander@^9.4.1:
version "9.5.0"
resolved "https://registry.yarnpkg.com/commander/-/commander-9.5.0.tgz#bc08d1eb5cedf7ccb797a96199d41c7bc3e60d30"
Expand Down Expand Up @@ -4209,6 +4228,11 @@ crypto-random-string@^4.0.0:
dependencies:
type-fest "^1.0.1"

[email protected]:
version "0.0.10"
resolved "https://registry.yarnpkg.com/cssfilter/-/cssfilter-0.0.10.tgz#c6d2672632a2e5c83e013e6864a42ce8defd20ae"
integrity sha512-FAaLDaplstoRsDR8XGYH51znUN0UY7nMc6Z9/fvE8EXGwvJE9hu7W2vHwx1+bd6gCYnln9nLbzxFTrcO9YQDZw==

dargs@^7.0.0:
version "7.0.0"
resolved "https://registry.yarnpkg.com/dargs/-/dargs-7.0.0.tgz#04015c41de0bcb69ec84050f3d9be0caf8d6d5cc"
Expand Down Expand Up @@ -10615,6 +10639,14 @@ [email protected]:
resolved "https://registry.yarnpkg.com/xregexp/-/xregexp-2.0.0.tgz#52a63e56ca0b84a7f3a5f3d61872f126ad7a5943"
integrity sha512-xl/50/Cf32VsGq/1R8jJE5ajH1yMCQkpmoS10QbFZWl2Oor4H0Me64Pu2yxvsRWK3m6soJbmGfzSR7BYmDcWAA==

xss@^1.0.8:
version "1.0.14"
resolved "https://registry.yarnpkg.com/xss/-/xss-1.0.14.tgz#4f3efbde75ad0d82e9921cc3c95e6590dd336694"
integrity sha512-og7TEJhXvn1a7kzZGQ7ETjdQVS2UfZyTlsEdDOqvQF7GoxNfY+0YLCzBy1kPdsDDx4QuNAonQPddpsn6Xl/7sw==
dependencies:
commander "^2.20.3"
cssfilter "0.0.10"

xtend@^4.0.0, xtend@^4.0.2, xtend@~4.0.1:
version "4.0.2"
resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54"
Expand Down

0 comments on commit 1e099fa

Please sign in to comment.