apollo-link-webworker
Apollo link that lets you use graphql client-side only, with a webworker as a "server" supporting normal query and subscriptions
Important note
This repository is just a proof of concept and not intended for production use yet. But contributions are welcomed :)
Installing
Install the package and its peer dependencies :
yarn add apollo-link-webworker graphql apollo-link subscriptions-transport-ws
Getting started
Start by creating a worker.js
file. Then you can import the utility functions that help you to build the worker :
worker.js
;
Creating the basic worker
createWorker
takes an option object as parameter accepting the schema and the context:
worker.js
; ; // your graphql schema; // your graphql context ;
If you only want to support classical communication (i.e : you don't mind about subscriptions) you can skip the next step.
Handling subscriptions
apollo-link-webworker
lets you generate graphql subscriptions from external event source. It's very useful when you don't own the socket server (firebase realtime database for example) but still need to resolve the result via your graphql schema.
To add subscriptions, just compose the handleSubscriptions
utility function inside the worker onmessage
handler :
worker.js
; ; // your graphql schema; // your graphql context; // a PubSub instance from graphql-subscriptions package for example ; self ;
pubsub.js
; const pubsub = ; ;
Whenever you need to generate a subscription from an external event source, you just need to push to the correct pubsub channel. By convention, the channel name used is the graphql subscription operation name.
For example (with firebase) : schema.js
; const schemaString = ` [...] type Subscription { messageAdded: Message! } [...] `; const resolvers = ... Subscription: messageAdded: pubsub ...;
OnMessageAdded.graphql
subscription OnMessageAdded messageAdded id content user id username
// Generates a subscriptions from external firebase event source;
Generating the apollo client
Once you created your worker.js
file you can instanciate a new WebWorkerLink
from the factory function createWebWorkerLink
:
client.js
;;; const GraphqlWorker = ; const worker = ; const link = ; const dataIdFromObject = resultid; const cache = dataIdFromObject ; const client = cache link; ;