Created
April 27, 2020 23:50
-
-
Save zaksabeast/b00074bcd09eb98b527c6ba04719b313 to your computer and use it in GitHub Desktop.
Short gist to demonstrate orchestrating web workers with Apollo client and comlink
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
// workers/multiply.js | |
import { expose } from 'comlink' | |
const multiply = (first, second) => first * second; | |
expose(multiply); | |
// graphql/client.js | |
import gql from 'graphql-tag'; | |
import { ApolloClient } from 'apollo-client'; | |
import { InMemoryCache } from 'apollo-cache-inmemory'; | |
import { wrap } from 'comlink' | |
const typeDefs = gql` | |
extend type Query { | |
multiply(first: Int!, second: Int!): Int! | |
} | |
`; | |
const multiply = wrap(new Worker('../workers/multiply.js')); | |
const resolvers = { | |
Query: { | |
multiply: (parent, args) => multiply(args.first, args.second), | |
}, | |
}; | |
export const client = new ApolloClient({ | |
cache: new InMemoryCache(), | |
resolvers, | |
typeDefs, | |
}); | |
// app.js | |
import gql from 'graphql-tag'; | |
import React from "react"; | |
import { useQuery } from '@apollo/react-hooks'; | |
const GET_MULTIPLICATION = gql` | |
query multiply($first: Int!, $second: Int!) { | |
multiply(first: $first, second: $second) @client | |
} | |
`; | |
export const App = () => { | |
const { data } = useQuery(GET_MULTIPLICATION, { | |
variables: { first: 2, second: 5 }, | |
}); | |
return ( | |
<div style={{ display: 'flex', justifyContent: 'center' }}> | |
<h3>Calculation from other thread: {data?.multiply}</h3> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment