Skip to content

Commit

Permalink
Allow SchemaLink.Options.context function to be async. (#6735)
Browse files Browse the repository at this point in the history
Closes #6730.
  • Loading branch information
benjamn authored Jul 29, 2020
1 parent c3f65bf commit d7664b5
Showing 1 changed file with 32 additions and 32 deletions.
64 changes: 32 additions & 32 deletions src/link/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import { ApolloLink, Operation, FetchResult } from '../core';
import { Observable } from '../../utilities';

export namespace SchemaLink {
export type ResolverContext = Record<string, any>;
export type ResolverContextFunction = (
operation: Operation,
) => Record<string, any>;
) => ResolverContext | PromiseLike<ResolverContext>;

export interface Options {
/**
Expand All @@ -23,48 +24,47 @@ export namespace SchemaLink {
/**
* A context to provide to resolvers declared within the schema.
*/
context?: ResolverContextFunction | Record<string, any>;
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<FetchResult> | null {
public request(operation: Operation): Observable<FetchResult> {
return new Observable<FetchResult>(observer => {
Promise.resolve(
execute(
this.schema,
operation.query,
this.rootValue,
new Promise<SchemaLink.ResolverContext>(
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);
}
});
});
}
}

0 comments on commit d7664b5

Please sign in to comment.