@datocms/svelte 3.0.2 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,6 +40,10 @@ Components:
40
40
  - [`<StructuredText />`](src/lib/components/StructuredText)
41
41
  - [`<Head />`](src/lib/components/Head)
42
42
 
43
+ Stores:
44
+
45
+ - [`querySubscription`](src/lib/stores/querySubscription)
46
+
43
47
  ## Installation
44
48
 
45
49
  ```
@@ -1,5 +1,7 @@
1
1
  <script>export let node;
2
- node;
3
2
  </script>
4
3
 
5
- <blockquote><slot /></blockquote>
4
+ <blockquote>
5
+ <slot />
6
+ <footer>{node.attribution}</footer>
7
+ </blockquote>
@@ -6,6 +6,7 @@ export { default as Head } from './components/Head/Head.svelte';
6
6
  export { default as Image } from './components/Image/Image.svelte';
7
7
  export { default as StructuredText } from './components/StructuredText/StructuredText.svelte';
8
8
  export { default as VideoPlayer } from './components/VideoPlayer/VideoPlayer.svelte';
9
+ export * from './stores/querySubscription';
9
10
  export type PredicateComponentTuple = [
10
11
  (n: Node) => boolean,
11
12
  new (...any: any) => SvelteComponent
package/package/index.js CHANGED
@@ -3,3 +3,4 @@ export { default as Head } from './components/Head/Head.svelte';
3
3
  export { default as Image } from './components/Image/Image.svelte';
4
4
  export { default as StructuredText } from './components/StructuredText/StructuredText.svelte';
5
5
  export { default as VideoPlayer } from './components/VideoPlayer/VideoPlayer.svelte';
6
+ export * from './stores/querySubscription';
@@ -0,0 +1,106 @@
1
+ # Live real-time updates
2
+
3
+ `querySubscription` returns a Svelte store that you can use to implement client-side updates of the page as soon as the content changes. It uses DatoCMS's [Real-time Updates API](https://www.datocms.com/docs/real-time-updates-api/api-reference) to receive the updated query results in real-time, and is able to reconnect in case of network failures.
4
+
5
+ Live updates are great both to get instant previews of your content while editing it inside DatoCMS, or to offer real-time updates of content to your visitors (ie. news site).
6
+
7
+ ## Table of Contents
8
+
9
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
10
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
11
+
12
+ - [Reference](#reference)
13
+ - [Initialization options](#initialization-options)
14
+ - [Connection status](#connection-status)
15
+ - [Error object](#error-object)
16
+ - [Example](#example)
17
+
18
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
19
+
20
+ ## Reference
21
+
22
+ Import `querySubscription` from `datocms-svelte` and use it inside your components like this:
23
+
24
+ ```js
25
+ import { querySubscription } from '@datocms/svelte';
26
+
27
+ const subscription = querySubscription(options: Options);
28
+ ```
29
+
30
+ ## Initialization options
31
+
32
+ | prop | type | required | description | default |
33
+ | ------------------ | ------------------------------------------------------------------------------------------ | ------------------ | ------------------------------------------------------------------ | ------------------------------------ |
34
+ | enabled | boolean | :x: | Whether the subscription has to be performed or not | true |
35
+ | query | string \| [`TypedDocumentNode`](https://github.com/dotansimha/graphql-typed-document-node) | :white_check_mark: | The GraphQL query to subscribe | |
36
+ | token | string | :white_check_mark: | DatoCMS API token to use | |
37
+ | variables | Object | :x: | GraphQL variables for the query | |
38
+ | preview | boolean | :x: | If true, the Content Delivery API with draft content will be used | false |
39
+ | environment | string | :x: | The name of the DatoCMS environment where to perform the query | defaults to primary environment |
40
+ | initialData | Object | :x: | The initial data to use on the first render | |
41
+ | reconnectionPeriod | number | :x: | In case of network errors, the period (in ms) to wait to reconnect | 1000 |
42
+ | 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 |
43
+ | 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 |
44
+ | baseUrl | string | :x: | The base URL to use to perform the query | `https://graphql-listen.datocms.com` |
45
+
46
+ ## Connection status
47
+
48
+ The `status` property represents the state of the server-sent events connection. It can be one of the following:
49
+
50
+ - `connecting`: the subscription channel is trying to connect
51
+ - `connected`: the channel is open, we're receiving live updates
52
+ - `closed`: the channel has been permanently closed due to a fatal error (ie. an invalid query)
53
+
54
+ ## Error object
55
+
56
+ | prop | type | description |
57
+ | -------- | ------ | ------------------------------------------------------- |
58
+ | code | string | The code of the error (ie. `INVALID_QUERY`) |
59
+ | message | string | An human friendly message explaining the error |
60
+ | response | Object | The raw response returned by the endpoint, if available |
61
+
62
+ ## Example
63
+
64
+ ```svelte
65
+ <script>
66
+ import { querySubscription } from 'react-datocms';
67
+
68
+ const subscription = useQuerySubscription({
69
+ enabled: true,
70
+ query: `
71
+ query AppQuery($first: IntType) {
72
+ allBlogPosts {
73
+ slug
74
+ title
75
+ }
76
+ }`,
77
+ variables: { first: 10 },
78
+ token: 'YOUR_API_TOKEN',
79
+ });
80
+
81
+ $: ({ data, error, status } = $subscription)
82
+
83
+ const statusMessage = {
84
+ connecting: 'Connecting to DatoCMS...',
85
+ connected: 'Connected to DatoCMS, receiving live updates!',
86
+ closed: 'Connection closed',
87
+ };
88
+ </script>
89
+
90
+ <p>Connection status: {statusMessage[status]}</p>
91
+
92
+ {#if error}
93
+ <h1>Error: {error.code}</h1>
94
+ <p>{error.message}</p>
95
+ {#if error.response}
96
+ <pre>{JSON.stringify(error.response, null, 2)}</pre>
97
+ {/if}
98
+ {/if}
99
+
100
+ {#if data}
101
+ <ul>
102
+ {#each data.allBlogPosts as blogPost (blogPost.slug)}
103
+ <li>{blogPost.title}</li>
104
+ </ul>
105
+ {/if}
106
+ ```
@@ -0,0 +1,24 @@
1
+ /// <reference types="svelte" />
2
+ import { type ChannelErrorData, type ConnectionStatus, type Options } from 'datocms-listen';
3
+ export type SubscribeToQueryOptions<QueryResult, QueryVariables> = Omit<Options<QueryResult, QueryVariables>, 'onStatusChange' | 'onUpdate' | 'onChannelError'>;
4
+ export type EnabledQuerySubscriptionOptions<QueryResult, QueryVariables> = {
5
+ /** Whether the subscription has to be performed or not */
6
+ enabled?: true;
7
+ /** The initial data to use while the initial request is being performed */
8
+ initialData?: QueryResult;
9
+ } & SubscribeToQueryOptions<QueryResult, QueryVariables>;
10
+ export type DisabledQuerySubscriptionOptions<QueryResult, QueryVariables> = {
11
+ /** Whether the subscription has to be performed or not */
12
+ enabled: false;
13
+ /** The initial data to use while the initial request is being performed */
14
+ initialData?: QueryResult;
15
+ } & Partial<SubscribeToQueryOptions<QueryResult, QueryVariables>>;
16
+ export type QuerySubscriptionOptions<QueryResult, QueryVariables> = EnabledQuerySubscriptionOptions<QueryResult, QueryVariables> | DisabledQuerySubscriptionOptions<QueryResult, QueryVariables>;
17
+ export type Subscription<QueryResult> = {
18
+ error: ChannelErrorData | null;
19
+ data: QueryResult | null;
20
+ status: ConnectionStatus | null;
21
+ };
22
+ export declare function querySubscription<QueryResult = unknown, QueryVariables = unknown>(options: QuerySubscriptionOptions<QueryResult, QueryVariables>): {
23
+ subscribe: (this: void, run: import("svelte/store").Subscriber<Subscription<QueryResult>>, invalidate?: import("svelte/store").Invalidator<Subscription<QueryResult>> | undefined) => import("svelte/store").Unsubscriber;
24
+ };
@@ -0,0 +1,44 @@
1
+ import { subscribeToQuery } from 'datocms-listen';
2
+ import { onMount } from 'svelte';
3
+ import { writable } from 'svelte/store';
4
+ export function querySubscription(options) {
5
+ const { enabled, initialData, ...other } = options;
6
+ const subscribeToQueryOptions = other;
7
+ const { subscribe, update } = writable({
8
+ error: null,
9
+ data: initialData || null,
10
+ status: enabled ? 'connecting' : 'closed'
11
+ });
12
+ onMount(() => {
13
+ if (enabled === false) {
14
+ update((old) => ({ ...old, status: 'closed' }));
15
+ return;
16
+ }
17
+ let unsubscribe;
18
+ async function subscribe() {
19
+ unsubscribe = await subscribeToQuery({
20
+ ...subscribeToQueryOptions,
21
+ onStatusChange: (status) => {
22
+ update((old) => ({ ...old, status }));
23
+ },
24
+ onUpdate: (updateData) => {
25
+ update((old) => ({
26
+ ...old,
27
+ error: null,
28
+ data: updateData.response.data
29
+ }));
30
+ },
31
+ onChannelError: (errorData) => {
32
+ update((old) => ({ ...old, error: errorData, data: null }));
33
+ }
34
+ });
35
+ }
36
+ subscribe();
37
+ return () => {
38
+ if (unsubscribe) {
39
+ unsubscribe();
40
+ }
41
+ };
42
+ });
43
+ return { subscribe };
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datocms/svelte",
3
- "version": "3.0.2",
3
+ "version": "3.0.4",
4
4
  "description": "A set of components and utilities to work faster with DatoCMS in Svelte",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -46,7 +46,8 @@
46
46
  "@typescript-eslint/eslint-plugin": "^5.62.0",
47
47
  "@typescript-eslint/parser": "^5.62.0",
48
48
  "csstype": "^3.1.3",
49
- "datocms-structured-text-generic-html-renderer": "^2.0.4",
49
+ "datocms-structured-text-generic-html-renderer": "^2.1.12",
50
+ "doctoc": "^2.0.0",
50
51
  "eslint": "^8.56.0",
51
52
  "eslint-config-prettier": "^8.10.0",
52
53
  "eslint-plugin-svelte": "^2.35.1",
@@ -60,11 +61,11 @@
60
61
  "tslib": "^2.6.2",
61
62
  "typescript": "^5.0.0",
62
63
  "vite": "^5.0.0",
63
- "vitest": "^1.0.0",
64
- "doctoc": "^2.0.0"
64
+ "vitest": "^1.0.0"
65
65
  },
66
66
  "type": "module",
67
67
  "dependencies": {
68
+ "datocms-listen": "^0.1.15",
68
69
  "datocms-structured-text-utils": "^4.0.1",
69
70
  "svelte-intersection-observer": "^1.0.0"
70
71
  },