Created
March 13, 2019 15:00
-
-
Save KillerCodeMonkey/59662b525f94c98a233e49c4d81d8c3b to your computer and use it in GitHub Desktop.
To run apollo client against a local schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ApolloLink, Observable } from 'apollo-link' | |
import { execute, GraphQLSchema } from 'graphql' | |
export class LocalLink extends ApolloLink { | |
schema: GraphQLSchema | |
constructor(schema: GraphQLSchema) { | |
super() | |
this.schema = schema | |
} | |
request(operation: any): Observable<any> { | |
const { schema } = this | |
const { query, variables, operationName } = operation | |
return new Observable((observer) => { | |
let canceled = false | |
// We get a MaybePromise from the execute function | |
Promise.resolve(execute(schema, query, null, null, variables, operationName)) | |
.then((result) => { | |
if (canceled) { | |
return null | |
} | |
// we have data and can send it to back up the link chain | |
observer.next(result) | |
observer.complete() | |
return result | |
}) | |
.catch((err) => { | |
if (canceled) { | |
return | |
} | |
observer.error(err) | |
}) | |
return () => { | |
canceled = true | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment