From d7664b5a075c9f45305e6983b79f254dbca63073 Mon Sep 17 00:00:00 2001 From: Ben Newman Date: Wed, 29 Jul 2020 14:58:28 -0400 Subject: [PATCH] Allow SchemaLink.Options.context function to be async. (#6735) Closes #6730. --- src/link/schema/index.ts | 64 ++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/src/link/schema/index.ts b/src/link/schema/index.ts index d2bde09767f..b11244a654d 100644 --- a/src/link/schema/index.ts +++ b/src/link/schema/index.ts @@ -5,9 +5,10 @@ import { ApolloLink, Operation, FetchResult } from '../core'; import { Observable } from '../../utilities'; export namespace SchemaLink { + export type ResolverContext = Record; export type ResolverContextFunction = ( operation: Operation, - ) => Record; + ) => ResolverContext | PromiseLike; export interface Options { /** @@ -23,48 +24,47 @@ export namespace SchemaLink { /** * A context to provide to resolvers declared within the schema. */ - context?: ResolverContextFunction | Record; + context?: ResolverContext | ResolverContextFunction; } } export class SchemaLink extends ApolloLink { - public schema: GraphQLSchema; - public rootValue: any; - public context: SchemaLink.ResolverContextFunction | any; + public schema: SchemaLink.Options["schema"]; + public rootValue: SchemaLink.Options["rootValue"]; + public context: SchemaLink.Options["context"]; - constructor({ schema, rootValue, context }: SchemaLink.Options) { + constructor(options: SchemaLink.Options) { super(); - - this.schema = schema; - this.rootValue = rootValue; - this.context = context; + this.schema = options.schema; + this.rootValue = options.rootValue; + this.context = options.context; } - public request(operation: Operation): Observable | null { + public request(operation: Operation): Observable { return new Observable(observer => { - Promise.resolve( - execute( - this.schema, - operation.query, - this.rootValue, + new Promise( + resolve => resolve( typeof this.context === 'function' ? this.context(operation) - : this.context, - operation.variables, - operation.operationName, - ), - ) - .then(data => { - if (!observer.closed) { - observer.next(data); - observer.complete(); - } - }) - .catch(error => { - if (!observer.closed) { - observer.error(error); - } - }); + : this.context + ) + ).then(context => execute( + this.schema, + operation.query, + this.rootValue, + context, + operation.variables, + operation.operationName, + )).then(data => { + if (!observer.closed) { + observer.next(data); + observer.complete(); + } + }).catch(error => { + if (!observer.closed) { + observer.error(error); + } + }); }); } }