Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

datocms-listen

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

datocms-listen

<!--datocms-autoinclude-header start-->

  • 1.0.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
32K
increased by17.66%
Maintainers
1
Weekly downloads
 
Created
Source

👉 Visit the DatoCMS homepage or see What is DatoCMS?


datocms-listen

MIT MIT Build Status

A lightweight, TypeScript-ready package that offers utilities to work with DatoCMS Real-time Updates API inside a browser.

Installation

npm install datocms-listen

Example

Import subscribeToQuery from datocms-listen and use it inside your components like this:

import { subscribeToQuery } from "datocms-listen";

const unsubscribe = await subscribeToQuery({
  query: `
    query BlogPosts($first: IntType!) {
      allBlogPosts(first: $first) {
        title
        nonExistingField
      }
    }
  `,
  variables: { first: 10 },
  token: "YOUR_TOKEN",
  includeDrafts: true,
  onUpdate: (update) => {
    // response is the GraphQL response
    console.log(update.response.data);
  },
  onStatusChange: (status) => {
    // status can be "connected", "connecting" or "closed"
    console.log(status);
  },
  onChannelError: (error) => {
    // error will be something like:
    // {
    //   code: "INVALID_QUERY",
    //   message: "The query returned an erroneous response. Please consult the response details to understand the cause.",
    //   response: {
    //     errors: [
    //       {
    //         fields: ["query", "allBlogPosts", "nonExistingField"],
    //         locations: [{ column: 67, line: 1 }],
    //         message: "Field 'nonExistingField' doesn't exist on type 'BlogPostRecord'",
    //       },
    //     ],
    //   },
    // }
    console.error(error);
  },
  onError: (error) => {
    // error will be
    // {
    //   message: "ERROR MESSAGE"
    // }
    console.log(error.message);
  },
  onEvent: (event) => {
    // event will be
    // {
    //   status: "connected|connected|closed",
    //   channelUrl: "...",
    //   message: "MESSAGE",
    // }
  },
});

Initialization options

proptyperequireddescriptiondefault
querystring | TypedDocumentNode:white_check_mark:The GraphQL query to subscribe
tokenstring:white_check_mark:DatoCMS API token to use
onUpdatefunction:white_check_mark:Callback function to receive query update events
onChannelErrorfunction:x:Callback function to receive channelError events
onStatusChangefunction:x:Callback function to receive status change events
onErrorfunction:x:Callback function to receive error events
onEventfunction:x:Callback function to receive other events
variablesObject:x:GraphQL variables for the query
includeDraftsboolean:x:If true, draft records will be returned
excludeInvalidboolean:x:If true, invalid records will be filtered out
environmentstring:x:The name of the DatoCMS environment where to perform the query (defaults to primary environment)
contentLink'vercel-1' or undefined:x:If true, embed metadata that enable Content Link
baseEditingUrlstring:x:The base URL of the DatoCMS project
cacheTagsboolean:x:If true, receive the Cache Tags associated with the query
reconnectionPeriodnumber:x:In case of network errors, the period (in ms) to wait to reconnect1000
fetchera fetch-like function:x:The fetch function to use to perform the registration querywindow.fetch
eventSourceClassan EventSource-like class:x:The EventSource class to use to open up the SSE connectionwindow.EventSource
baseUrlstring:x:The base URL to use to perform the queryhttps://graphql-listen.datocms.com

Events

onUpdate(update: UpdateData<QueryResult>)

This function will be called everytime the channel sends an updated query result. The updateData argument has the following properties:

proptypedescription
responseObjectThe GraphQL updated response

onStatusChange(status: ConnectionStatus)

The status argument represents the state of the server-sent events connection. It can be one of the following:

  • connecting: the subscription channel is trying to connect
  • connected: the channel is open, we're receiving live updates
  • closed: the channel has been permanently closed due to a fatal error (ie. an invalid query)

onChannelError(errorData: ChannelErrorData)

The errorData argument has the following properties:

proptypedescription
codestringThe code of the error (ie. INVALID_QUERY)
messagestringAn human friendly message explaining the error
responseObjectThe raw response returned by the endpoint, if available

onError(error: ErrorData)

This function is called when connection errors occur.

The error argument has the following properties:

proptypedescription
messagestringAn human friendly message explaining the error

onEvent(event: EventData)

This function is called then other events occur.

The event argument has the following properties:

proptypedescription
statusstringThe current connection status (see above)
channelUrlstringThe current channel URL
messagestringAn human friendly message explaining the event

Return value

The function returns a Promise<() => void>. You can call the function to gracefully close the SSE channel.


What is DatoCMS?

DatoCMS is the REST & GraphQL Headless CMS for the modern web.

Trusted 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, content editors and marketers!

Quick links:

Our featured repos:

Or see all our public repos

FAQs

Package last updated on 13 Aug 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc