{"id":13880833,"url":"https://github.com/datocms/datocms-listen","last_synced_at":"2025-04-27T03:32:44.695Z","repository":{"id":45258748,"uuid":"310036398","full_name":"datocms/datocms-listen","owner":"datocms","description":"A lightweight, TypeScript-ready package that offers utilities to work with DatoCMS Real-time Updates API inside a browser.","archived":false,"fork":false,"pushed_at":"2025-02-06T08:11:36.000Z","size":10341,"stargazers_count":10,"open_issues_count":0,"forks_count":0,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-04-15T20:02:13.236Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/datocms.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-04T15:04:14.000Z","updated_at":"2025-02-06T08:11:40.000Z","dependencies_parsed_at":"2024-06-18T20:05:04.553Z","dependency_job_id":"f728518d-1662-4cec-89b5-7f8f05eaa02e","html_url":"https://github.com/datocms/datocms-listen","commit_stats":{"total_commits":59,"total_committers":5,"mean_commits":11.8,"dds":0.2033898305084746,"last_synced_commit":"30bf2685f403ccfe43f70b8677df139f3f874381"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fdatocms-listen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fdatocms-listen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fdatocms-listen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fdatocms-listen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/datocms","download_url":"https://codeload.github.com/datocms/datocms-listen/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251027154,"owners_count":21525084,"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":[],"created_at":"2024-08-06T08:03:31.770Z","updated_at":"2025-04-27T03:32:39.687Z","avatar_url":"https://github.com/datocms.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"\u003c!--datocms-autoinclude-header start--\u003e\n\n\u003ca href=\"https://www.datocms.com/\"\u003e\u003cimg src=\"https://www.datocms.com/images/full_logo.svg\" height=\"60\"\u003e\u003c/a\u003e\n\n👉 [Visit the DatoCMS homepage](https://www.datocms.com) or see [What is DatoCMS?](#what-is-datocms)\n\n---\n\n\u003c!--datocms-autoinclude-header end--\u003e\n\n# datocms-listen\n\n![MIT](https://img.shields.io/npm/l/datocms-listen?style=for-the-badge) ![MIT](https://img.shields.io/npm/v/datocms-listen?style=for-the-badge) [![Build Status](https://img.shields.io/travis/datocms/datocms-listen?style=for-the-badge)](https://travis-ci.org/datocms/datocms-listen)\n\nA lightweight, TypeScript-ready package that offers utilities to work with DatoCMS [Real-time Updates API](https://www.datocms.com/docs/real-time-updates-api) inside a browser.\n\n## Installation\n\n```\nnpm install datocms-listen\n```\n\n## Example\n\nImport `subscribeToQuery` from `datocms-listen` and use it inside your components like this:\n\n```js\nimport { subscribeToQuery } from \"datocms-listen\";\n\nconst unsubscribe = await subscribeToQuery({\n  query: `\n    query BlogPosts($first: IntType!) {\n      allBlogPosts(first: $first) {\n        title\n        nonExistingField\n      }\n    }\n  `,\n  variables: { first: 10 },\n  token: \"YOUR_TOKEN\",\n  includeDrafts: true,\n  onUpdate: (update) =\u003e {\n    // response is the GraphQL response\n    console.log(update.response.data);\n  },\n  onStatusChange: (status) =\u003e {\n    // status can be \"connected\", \"connecting\" or \"closed\"\n    console.log(status);\n  },\n  onChannelError: (error) =\u003e {\n    // error will be something like:\n    // {\n    //   code: \"INVALID_QUERY\",\n    //   message: \"The query returned an erroneous response. Please consult the response details to understand the cause.\",\n    //   response: {\n    //     errors: [\n    //       {\n    //         fields: [\"query\", \"allBlogPosts\", \"nonExistingField\"],\n    //         locations: [{ column: 67, line: 1 }],\n    //         message: \"Field 'nonExistingField' doesn't exist on type 'BlogPostRecord'\",\n    //       },\n    //     ],\n    //   },\n    // }\n    console.error(error);\n  },\n  onError: (error) =\u003e {\n    // error will be\n    // {\n    //   message: \"ERROR MESSAGE\"\n    // }\n    console.log(error.message);\n  },\n  onEvent: (event) =\u003e {\n    // event will be\n    // {\n    //   status: \"connected|connected|closed\",\n    //   channelUrl: \"...\",\n    //   message: \"MESSAGE\",\n    // }\n  },\n});\n```\n\n## Initialization options\n\n| prop               | type                                                                                       | required           | description                                                                                      | default                              |\n| ------------------ | ------------------------------------------------------------------------------------------ | ------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------ |\n| query              | string \\| [`TypedDocumentNode`](https://github.com/dotansimha/graphql-typed-document-node) | :white_check_mark: | The GraphQL query to subscribe                                                                   |                                      |\n| token              | string                                                                                     | :white_check_mark: | DatoCMS API token to use                                                                         |                                      |\n| onUpdate           | function                                                                                   | :white_check_mark: | Callback function to receive query update events                                                 |                                      |\n| onChannelError     | function                                                                                   | :x:                | Callback function to receive channelError events                                                 |                                      |\n| onStatusChange     | function                                                                                   | :x:                | Callback function to receive status change events                                                |                                      |\n| onError            | function                                                                                   | :x:                | Callback function to receive error events                                                        |                                      |\n| onEvent            | function                                                                                   | :x:                | Callback function to receive other events                                                        |                                      |\n| variables          | Object                                                                                     | :x:                | GraphQL variables for the query                                                                  |                                      |\n| includeDrafts      | boolean                                                                                    | :x:                | If true, draft records will be returned                                                          |                                      |\n| excludeInvalid     | boolean                                                                                    | :x:                | If true, invalid records will be filtered out                                                    |                                      |\n| environment        | string                                                                                     | :x:                | The name of the DatoCMS environment where to perform the query (defaults to primary environment) |                                      |\n| contentLink        | `'vercel-1'` or `undefined`                                                                | :x:                | If true, embed metadata that enable Content Link                                                 |                                      |\n| baseEditingUrl     | string                                                                                     | :x:                | The base URL of the DatoCMS project                                                              |                                      |\n| cacheTags          | boolean                                                                                    | :x:                | If true, receive the Cache Tags associated with the query                                        |                                      |\n| reconnectionPeriod | number                                                                                     | :x:                | In case of network errors, the period (in ms) to wait to reconnect                               | 1000                                 |\n| fetcher            | a [fetch-like function](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)        | :x:                | The fetch function to use to perform the registration query                                      | window.fetch                         |\n| eventSourceClass   | an [EventSource-like](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) class  | :x:                | The EventSource class to use to open up the SSE connection                                       | window.EventSource                   |\n| baseUrl            | string                                                                                     | :x:                | The base URL to use to perform the query                                                         | `https://graphql-listen.datocms.com` |\n\n## Events\n\n### `onUpdate(update: UpdateData\u003cQueryResult\u003e)`\n\nThis function will be called everytime the channel sends an updated query result. The `updateData` argument has the following properties:\n\n| prop     | type   | description                  |\n| -------- | ------ | ---------------------------- |\n| response | Object | The GraphQL updated response |\n\n### `onStatusChange(status: ConnectionStatus)`\n\nThe `status` argument represents the state of the server-sent events connection. It can be one of the following:\n\n- `connecting`: the subscription channel is trying to connect\n- `connected`: the channel is open, we're receiving live updates\n- `closed`: the channel has been permanently closed due to a fatal error (ie. an invalid query)\n\n### `onChannelError(errorData: ChannelErrorData)`\n\nThe `errorData` argument has the following properties:\n\n| prop     | type   | description                                             |\n| -------- | ------ | ------------------------------------------------------- |\n| code     | string | The code of the error (ie. `INVALID_QUERY`)             |\n| message  | string | An human friendly message explaining the error          |\n| response | Object | The raw response returned by the endpoint, if available |\n\n### `onError(error: ErrorData)`\n\nThis function is called when connection errors occur.\n\nThe `error` argument has the following properties:\n\n| prop    | type   | description                                    |\n| ------- | ------ | ---------------------------------------------- |\n| message | string | An human friendly message explaining the error |\n\n### `onEvent(event: EventData)`\n\nThis function is called then other events occur.\n\nThe `event` argument has the following properties:\n\n| prop       | type   | description                                    |\n| ---------- | ------ | ---------------------------------------------- |\n| status     | string | The current connection status (see above)      |\n| channelUrl | string | The current channel URL                        |\n| message    | string | An human friendly message explaining the event |\n\n## Return value\n\nThe function returns a `Promise\u003c() =\u003e void\u003e`. You can call the function to gracefully close the SSE channel.\n\n\u003c!--datocms-autoinclude-footer start--\u003e\n\n---\n\n# What is DatoCMS?\n\u003ca href=\"https://www.datocms.com/\"\u003e\u003cimg src=\"https://www.datocms.com/images/full_logo.svg\" height=\"60\"\u003e\u003c/a\u003e\n\n[DatoCMS](https://www.datocms.com/) is the REST \u0026 GraphQL Headless CMS for the modern web.\n\nTrusted by over 25,000 enterprise businesses, agency partners, and individuals across the world, DatoCMS users create online content at scale from a central hub and distribute it via API. We ❤️ our [developers](https://www.datocms.com/team/best-cms-for-developers), [content editors](https://www.datocms.com/team/content-creators) and [marketers](https://www.datocms.com/team/cms-digital-marketing)!\n\n**Quick links:**\n\n- ⚡️ Get started with a [free DatoCMS account](https://dashboard.datocms.com/signup)\n- 🔖 Go through the [docs](https://www.datocms.com/docs)\n- ⚙️ Get [support from us and the community](https://community.datocms.com/)\n- 🆕 Stay up to date on new features and fixes on the [changelog](https://www.datocms.com/product-updates)\n\n**Our featured repos:**\n- [datocms/react-datocms](https://github.com/datocms/react-datocms): React helper components for images, Structured Text rendering, and more\n- [datocms/js-rest-api-clients](https://github.com/datocms/js-rest-api-clients): Node and browser JavaScript clients for updating and administering your content. For frontend fetches, we recommend using our [GraphQL Content Delivery API](https://www.datocms.com/docs/content-delivery-api) instead.\n- [datocms/cli](https://github.com/datocms/cli): Command-line interface that includes our [Contentful importer](https://github.com/datocms/cli/tree/main/packages/cli-plugin-contentful) and [Wordpress importer](https://github.com/datocms/cli/tree/main/packages/cli-plugin-wordpress)\n- [datocms/plugins](https://github.com/datocms/plugins): Example plugins we've made that extend the editor/admin dashboard\n- [DatoCMS Starters](https://www.datocms.com/marketplace/starters) has examples for various Javascript frontend frameworks\n\nOr see [all our public repos](https://github.com/orgs/datocms/repositories?q=\u0026type=public\u0026language=\u0026sort=stargazers)\n\n\u003c!--datocms-autoinclude-footer end--\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatocms%2Fdatocms-listen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdatocms%2Fdatocms-listen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatocms%2Fdatocms-listen/lists"}