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

Migrate to Apollo Server v4 #2797

Merged
merged 4 commits into from
May 1, 2023
Merged
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
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,21 @@
"type-check": "tsc -p tsconfig.check.json"
},
"dependencies": {
"@apollo/server": "^4.7.0",
"@apollo/subgraph": "^2.4.2",
"@aws-sdk/client-s3": "^3.262.0",
"@aws-sdk/s3-request-presigner": "^3.262.0",
"@faker-js/faker": "^7.6.0",
"@golevelup/nestjs-discovery": "^3.0.0",
"@nestjs/apollo": "^10.1.7",
"@nestjs/common": "^9.3.1",
"@nestjs/core": "^9.3.1",
"@nestjs/graphql": "^10.1.7",
"@nestjs/platform-express": "^9.3.1",
"@nestjs/apollo": "^11.0.5",
"@nestjs/common": "^9.4.0",
"@nestjs/core": "^9.4.0",
"@nestjs/graphql": "^11.0.5",
"@nestjs/platform-express": "^9.4.0",
"@patarapolw/prettyprint": "^1.0.3",
"@seedcompany/common": ">=0.10 <1",
"@seedcompany/data-loader": "^0.4.0",
"@seedcompany/nestjs-email": "^3.1.0",
"apollo-server-core": "^3.11.1",
"apollo-server-express": "^3.11.1",
"argon2": "^0.30.3",
"aws-xray-sdk-core": "^3.4.1",
"class-transformer": "^0.5.1",
Expand Down
6 changes: 3 additions & 3 deletions src/common/filter-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { applyDecorators } from '@nestjs/common';
import { Field } from '@nestjs/graphql';
import { Transform, Type } from 'class-transformer';
import { ValidateNested } from 'class-validator';
import { HasRequiredKeys } from 'type-fest';
import { Constructor, HasRequiredKeys } from 'type-fest';
import { DefaultValue } from './default-value';
import { AbstractClassType } from './types';

Expand All @@ -22,9 +22,9 @@ export const FilterField = <T extends object>(
...(options?.internal
? []
: [
Field(() => type, {
Field(() => type as unknown as Constructor<T>, {
nullable: true,
defaultValue: {}, // Only for GQL schema & not always applied in TS
defaultValue: {} as unknown as T, // Only for GQL schema & not always applied in TS
}),
]),
Type(() => type),
Expand Down
5 changes: 3 additions & 2 deletions src/common/secured-property.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Type } from '@nestjs/common';
import {
Field,
FieldOptions,
Expand Down Expand Up @@ -132,7 +133,7 @@ function InnerSecuredProperty<
abstract class SecuredPropertyClass
implements ISecured, Secured<SecuredValue<TsType, Nullable>>
{
@Field(() => valueClass, {
@Field(() => valueClass as Type<GqlType>, {
...options,
nullable: true,
})
Expand Down Expand Up @@ -191,7 +192,7 @@ function SecuredList<GQL, TS, Nullable extends boolean | undefined = false>(
abstract class SecuredPropertyListClass
implements ISecured, Secured<SecuredList<TS, Nullable>>
{
@Field(() => [valueClass], {
@Field(() => [valueClass as Type<GQL>], {
nullable: options.nullable,
})
readonly value: SecuredList<TS, Nullable>;
Expand Down
14 changes: 7 additions & 7 deletions src/core/graphql/gql-context.host.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
ApolloServerPlugin as ApolloPlugin,
GraphQLRequestContext as RequestContext,
GraphQLRequestListener as RequestListener,
} from '@apollo/server';
import { Plugin } from '@nestjs/apollo';
import {
CallHandler,
Expand All @@ -8,11 +13,6 @@ import {
OnModuleDestroy,
} from '@nestjs/common';
import { GqlContextType as ContextKey } from '@nestjs/graphql';
import {
ApolloServerPlugin as ApolloPlugin,
GraphQLRequestListener as RequestListener,
} from 'apollo-server-plugin-base';
import { GraphQLRequestContext as RequestContext } from 'apollo-server-types';
import { AsyncLocalStorage } from 'async_hooks';
import { Request, Response } from 'express';
import { GqlContextType as ContextType } from '~/common';
Expand Down Expand Up @@ -94,7 +94,7 @@ export class GqlContextHostImpl
* Attach GQL context to the ALS store now that we have it.
*/
async requestDidStart({
context,
contextValue: context,
}: RequestContext<ContextType>): Promise<RequestListener<ContextType>> {
const store = this.als.getStore();
if (!store) {
Expand All @@ -103,7 +103,7 @@ export class GqlContextHostImpl
store.ctx = context;
return {
async didResolveOperation({ operation }) {
context.operation = operation;
context.operation = operation!;
},
};
}
Expand Down
6 changes: 3 additions & 3 deletions src/core/graphql/graphql-logging.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Plugin } from '@nestjs/apollo';
import { GraphQLRequestContext as RequestContext } from 'apollo-server-core';
import {
ApolloServerPlugin as ApolloPlugin,
GraphQLRequestContext as RequestContext,
GraphQLRequestListener as RequestListener,
} from 'apollo-server-plugin-base';
} from '@apollo/server';
import { Plugin } from '@nestjs/apollo';
import { GraphQLError } from 'graphql';
import { Neo4jError } from 'neo4j-driver';
import { GqlContextType as ContextType } from '../../common';
Expand Down
8 changes: 4 additions & 4 deletions src/core/graphql/graphql-tracing.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Plugin } from '@nestjs/apollo';
import { FieldMiddleware } from '@nestjs/graphql';
import {
ApolloServerPlugin as ApolloPlugin,
GraphQLRequestExecutionListener as ExecutionListener,
GraphQLRequestListener as Listener,
} from 'apollo-server-plugin-base';
} from '@apollo/server';
import { Plugin } from '@nestjs/apollo';
import { FieldMiddleware } from '@nestjs/graphql';
import { GraphQLResolveInfo as ResolveInfo, ResponsePath } from 'graphql';
import { GqlContextType as ContextType } from '../../common';
import { Segment, TracingService } from '../tracing';
Expand Down Expand Up @@ -42,7 +42,7 @@ export class GraphqlTracingPlugin implements ApolloPlugin<ContextType> {

return {
executionDidEnd: async (err) => {
const userId = reqContext.context.session?.userId;
const userId = reqContext.contextValue.session?.userId;
if (userId) {
segment.setUser?.(userId);
}
Expand Down
99 changes: 52 additions & 47 deletions src/core/graphql/graphql.config.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import { KeyValueCacheSetOptions } from '@apollo/utils.keyvaluecache/src/KeyValueCache';
import { ApolloDriverConfig } from '@nestjs/apollo';
import { Injectable } from '@nestjs/common';
import { GqlOptionsFactory } from '@nestjs/graphql';
import { ContextFunction, PersistedQueryOptions } from '@apollo/server';
import {
ApolloServerErrorCode as ApolloCode,
unwrapResolverError,
} from '@apollo/server/errors';
import { ExpressContextFunctionArgument } from '@apollo/server/express4';
import {
ApolloServerPluginLandingPageLocalDefault,
ApolloServerPluginLandingPageProductionDefault,
ContextFunction,
KeyValueCache,
} from 'apollo-server-core';
import { PersistedQueryOptions } from 'apollo-server-core/src/graphqlOptions';
} from '@apollo/server/plugin/landingPage/default';
import {
PersistedQueryNotFoundError,
PersistedQueryNotSupportedError,
SyntaxError,
ValidationError,
} from 'apollo-server-errors';
import { Request, Response } from 'express';
KeyValueCache,
KeyValueCacheSetOptions,
} from '@apollo/utils.keyvaluecache';
import { ApolloDriverConfig } from '@nestjs/apollo';
import { Injectable } from '@nestjs/common';
import { GqlOptionsFactory } from '@nestjs/graphql';
import { setHas, setOf } from '@seedcompany/common';
import {
GraphQLErrorExtensions as ErrorExtensions,
GraphQLFormattedError as FormattedError,
GraphQLError,
GraphQLFormattedError,
GraphQLScalarType,
OperationDefinitionNode,
} from 'graphql';
import { compact } from 'lodash';
import {
GqlContextType,
JsonSet,
Expand All @@ -36,8 +38,9 @@ import { GraphqlTracingPlugin } from './graphql-tracing.plugin';

declare module 'graphql/error/GraphQLError' {
interface GraphQLErrorExtensions {
code: string;
code?: string;
codes?: ReadonlySet<string>;
stacktrace?: string[];
}
}

Expand Down Expand Up @@ -65,11 +68,11 @@ export class GraphQLConfig implements GqlOptionsFactory {
return {
autoSchemaFile: 'schema.graphql',
context: this.context,
cors: this.config.cors,
playground: false,
introspection: true,
formatError: this.formatError,
debug: this.debug,
includeStacktraceInErrorResponses: true,
status400ForVariableCoercionErrors: true, // will be default in v5
sortSchema: true,
buildSchemaOptions: {
fieldMiddleware: [this.tracing.fieldMiddleware()],
Expand Down Expand Up @@ -99,50 +102,43 @@ export class GraphQLConfig implements GqlOptionsFactory {
};
}

get debug() {
return true; // TODO
}
context: ContextFunction<[ExpressContextFunctionArgument], GqlContextType> =
async ({ req, res }) => ({
request: req,
response: res,
operation: createFakeStubOperation(),
});

context: ContextFunction<{ req: Request; res: Response }, GqlContextType> = ({
req,
res,
}) => ({
request: req,
response: res,
operation: createFakeStubOperation(),
});
formatError = (
formatted: FormattedError,
error: unknown | /* but probably a */ GraphQLError,
): FormattedError => {
// Probably the actual error thrown
const _original = unwrapResolverError(error);

formatError = (error: GraphQLError): GraphQLFormattedError => {
const extensions = { ...error.extensions };
const extensions: ErrorExtensions = { ...formatted.extensions };

const codes = (extensions.codes ??= new JsonSet(
this.resolveCodes(error, extensions.code),
compact(this.resolveCodes(formatted, extensions.code)),
));
delete extensions.code;

// Schema & validation errors don't have meaningful stack traces, so remove them
const worthlessTrace = codes.has('Validation') || codes.has('GraphQL');

if (!this.debug || worthlessTrace) {
delete extensions.exception;
if (worthlessTrace) {
delete extensions.stacktrace;
}

return {
message: error.message,
message: formatted.message,
extensions,
locations: error.locations,
path: error.path,
locations: formatted.locations,
path: formatted.path,
};
};

private resolveCodes(error: GraphQLError, code: string): string[] {
if (
[
ValidationError,
SyntaxError,
PersistedQueryNotFoundError,
PersistedQueryNotSupportedError,
].some((cls) => error instanceof cls)
) {
private resolveCodes(error: FormattedError, code?: string) {
if (code && setHas(apolloErrorCodesThatAreClientProblem, code)) {
return [code, 'GraphQL', 'Client'];
}
if (
Expand Down Expand Up @@ -195,3 +191,12 @@ class GraphQLCacheAdapter implements KeyValueCache {
await this.cache.delete(this.prefix + key);
}
}

const apolloErrorCodesThatAreClientProblem = setOf([
ApolloCode.GRAPHQL_PARSE_FAILED,
ApolloCode.GRAPHQL_VALIDATION_FAILED,
ApolloCode.PERSISTED_QUERY_NOT_FOUND,
ApolloCode.PERSISTED_QUERY_NOT_SUPPORTED,
ApolloCode.BAD_USER_INPUT,
ApolloCode.BAD_REQUEST,
]);
2 changes: 1 addition & 1 deletion test/utility/expect-gql-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ expect.extend({
'code',
'codes',
'status',
'exception',
'stacktrace',
),
};

Expand Down
Loading
Loading