{"id":13725560,"url":"https://github.com/PCreations/apollo-link-webworker","last_synced_at":"2025-05-07T20:32:59.206Z","repository":{"id":46933351,"uuid":"103674675","full_name":"PCreations/apollo-link-webworker","owner":"PCreations","description":"Apollo link that lets you use graphql client-side only, with a webworker as a \"server\" supporting normal queries and subscriptions","archived":false,"fork":false,"pushed_at":"2022-12-07T09:53:16.000Z","size":353,"stargazers_count":96,"open_issues_count":15,"forks_count":8,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-10-14T06:38:12.916Z","etag":null,"topics":["apollo-client","apollo-subscription","graphql","webworkers"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PCreations.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-09-15T15:48:21.000Z","updated_at":"2024-06-04T10:57:53.000Z","dependencies_parsed_at":"2023-01-24T16:31:15.774Z","dependency_job_id":null,"html_url":"https://github.com/PCreations/apollo-link-webworker","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PCreations%2Fapollo-link-webworker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PCreations%2Fapollo-link-webworker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PCreations%2Fapollo-link-webworker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PCreations%2Fapollo-link-webworker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PCreations","download_url":"https://codeload.github.com/PCreations/apollo-link-webworker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224645423,"owners_count":17346155,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apollo-client","apollo-subscription","graphql","webworkers"],"created_at":"2024-08-03T01:02:27.369Z","updated_at":"2024-11-14T15:31:31.402Z","avatar_url":"https://github.com/PCreations.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# apollo-link-webworker\nApollo link that lets you use graphql client-side only, with a webworker as a \"server\" supporting normal query and subscriptions\n\n# Important note\nThis repository is just a proof of concept and not intended for production use yet. But contributions are welcomed :)\n\n# Installing\nInstall the package and its peer dependencies :\n`yarn add apollo-link-webworker graphql apollo-link subscriptions-transport-ws`\n\n# Getting started\nStart by creating a `worker.js` file. Then you can import the utility functions that help you to build the worker :\n\n*worker.js*\n```javascript\nimport { createWorker, handleSubscriptions } from 'apollo-link-webworker';\n```\n\n## Creating the basic worker\n\n`createWorker` takes an option object as parameter accepting the schema and the context:\n\n*worker.js*\n```javascript\nimport { createWorker, handleSubscriptions } from 'apollo-link-webworker';\n\nimport schema from './schema'; // your graphql schema\nimport context from './context'; // your graphql context\n\ncreateWorker({\n  schema,\n  context\n});\n```\n\n## Configuring the webpack worker-loader\n\nIn order to `require` the worker file, you'll need to add the `worker-loader` to your webpack configuration :\n\n`yarn add worker-loader --dev`\n\nThen, with an ejected `react-app` for example, edit the `config/webpack.config.[dev/prod].js` files to add the specific loader :\n\n```\n[...]\nmodule: {\n    strictExportPresence: true,\n    rules: [\n      // TODO: Disable require.ensure as it's not a standard language feature.\n      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.\n      // { parser: { requireEnsure: false } },\n\n      // First, run the linter.\n      // It's important to do this before Babel processes the JS.\n      {\n        test: /\\.(js|jsx|mjs)$/,\n        enforce: 'pre',\n        use: [\n          {\n            options: {\n              formatter: eslintFormatter,\n              eslintPath: require.resolve('eslint'),\n              \n            },\n            loader: require.resolve('eslint-loader'),\n          },\n        ],\n        include: paths.appSrc,\n      },\n      {\n        // \"oneOf\" will traverse all following loaders until one will\n        // match the requirements. When no loader matches it will fall\n        // back to the \"file\" loader at the end of the loader list.\n        oneOf: [\n          {\n            test: /worker\\.js$/,  //worker.js is the filename I chose\n            include: path.appSrc,\n            loader: require.resolve('worker-loader'),\n          },\n          // \"url\" loader works like \"file\" loader except that it embeds assets\n          // smaller than specified limit in bytes as data URLs to avoid requests.\n          // A missing `test` is equivalent to a match.\n          {\n            test: [/\\.bmp$/, /\\.gif$/, /\\.jpe?g$/, /\\.png$/],\n            loader: require.resolve('url-loader'),\n            options: {\n              limit: 10000,\n              name: 'static/media/[name].[hash:8].[ext]',\n            },\n          },\n[...]\n```\n\nIf you only want to support classical communication (i.e : you don't mind about subscriptions) you can skip the next step.\n\n## Handling subscriptions\n\n`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.\n\nTo add subscriptions, just compose the `handleSubscriptions` utility function inside the worker `onmessage` handler :\n\n*worker.js*\n```javascript\nimport { createWorker, handleSubscriptions } from 'apollo-link-webworker';\n\nimport schema from './schema'; // your graphql schema\nimport context from './context'; // your graphql context\nimport pubsub from './pubsub'; // a PubSub instance from graphql-subscriptions package for example\n\ncreateWorker({\n  schema,\n  context\n});\n\nself.onmessage = message =\u003e handleSubscriptions({\n  self,\n  message,\n  schema,\n  context,\n  pubsub,\n});\n```\n\n*pubsub.js*\n```javascript\nimport { PubSub } from 'graphql-subscriptions';\n\nconst pubsub = new PubSub();\n\nexport default pubsub;\n```\n\nWhenever 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.\n\nFor example (with firebase) :\n*schema.js*\n```javascript\nimport pubsub from './pubsub';\n\nconst schemaString = `\n  [...]\n\n  type Subscription {\n    messageAdded: Message!\n  }\n\n  [...]\n\n`;\n\nconst resolvers = {\n  [...]\n  Subscription: {\n    messageAdded: {\n      subscribe: () =\u003e pubsub.asyncIterator('OnMessageAdded'),\n    },\n  }\n  [...]\n};\n```\n\n*OnMessageAdded.graphql*\n```javascript\nsubscription OnMessageAdded {\n  messageAdded {\n    id\n    content\n    user {\n      id\n      username\n    }\n  }\n}\n```\n\n```javascript\n// Generates a subscriptions from external firebase event source\nfirebaseDb().ref('/messages').on('child_added', snapshot =\u003e pubsub.publish('OnMessageAdded', {\n messageAdded: snapshot.val()\n}));\n```\n\n## Generating the apollo client\n\nOnce you created your `worker.js` file you can instanciate a new `WebWorkerLink` from the factory function `createWebWorkerLink` :\n\n*client.js*\n```javascript\nimport { ApolloClient } from 'apollo-client';\nimport InMemoryCache from 'apollo-cache-inmemory';\nimport { createWebWorkerLink } from 'apollo-link-webworker';\n\nconst GraphqlWorker = require('./worker.js');\n\nconst worker = new GraphqlWorker();\n\nconst link = createWebWorkerLink({ worker });\n\nconst dataIdFromObject = result =\u003e result.id;\n\nconst cache = new InMemoryCache({ dataIdFromObject });\n\nconst client = new ApolloClient({\n  cache,\n  link,\n});\n\nexport default client;\n```\n\n# Example chat application with Firebase \u0026 Authentication :\n[Firechat repository](https://github.com/PCreations/firechat)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPCreations%2Fapollo-link-webworker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FPCreations%2Fapollo-link-webworker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPCreations%2Fapollo-link-webworker/lists"}