@sanity/client 5.0.0 → 5.2.0

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
@@ -48,7 +48,7 @@ export async function updateDocumentTitle(_id, title) {
48
48
  }
49
49
  ```
50
50
 
51
- # Table of contents<!-- omit in toc -->
51
+ # Table of contents
52
52
 
53
53
  - [QuickStart](#quickstart)
54
54
  - [Requirements](#requirements)
@@ -88,6 +88,7 @@ export async function updateDocumentTitle(_id, title) {
88
88
  - [Examples: Specify image metadata to extract](#examples-specify-image-metadata-to-extract)
89
89
  - [Deleting an asset](#deleting-an-asset)
90
90
  - [Mutation options](#mutation-options)
91
+ - [Aborting a request](#aborting-a-request)
91
92
  - [Get client configuration](#get-client-configuration)
92
93
  - [Set client configuration](#set-client-configuration)
93
94
  - [Release new version](#release-new-version)
@@ -846,6 +847,49 @@ The following options are available for mutations, and can be applied either as
846
847
  - `dryRun` (`true|false`) - default `false`. If true, the mutation will be a dry run - the response will be identical to the one returned had this property been omitted or false (including error responses) but no documents will be affected.
847
848
  - `autoGenerateArrayKeys` (`true|false`) - default `false`. If true, the mutation API will automatically add `_key` attributes to objects in arrays that is missing them. This makes array operations more robust by having a unique key within the array available for selections, which helps prevent race conditions in real-time, collaborative editing.
848
849
 
850
+ ### Aborting a request
851
+
852
+ Requests can be aborted (or cancelled) in two ways:
853
+
854
+ #### 1. Abort a request by passing an [AbortSignal] with the request options
855
+
856
+ Sanity Client supports the [AbortController] API and supports receiving an abort signal that can be used to cancel the request. Here's an example that will abort the request if it takes more than 200ms to complete:
857
+
858
+ ```js
859
+ const abortController = new AbortController()
860
+
861
+ // note the lack of await here
862
+ const request = getClient().fetch('*[_type == "movie"]', {}, {signal: abortController.signal})
863
+
864
+ // this will abort the request after 200ms
865
+ setTimeout(() => abortController.abort(), 200)
866
+
867
+ try {
868
+ const response = await request
869
+ //…
870
+ } catch (error) {
871
+ if (error.name === 'AbortError') {
872
+ console.log('Request was aborted')
873
+ } else {
874
+ // rethrow in case of other errors
875
+ throw error
876
+ }
877
+ }
878
+ ```
879
+
880
+ #### 2. Cancel a request by unsubscribing from the Observable
881
+
882
+ When using the Observable API (e.g. `client.observable.fetch()`), you can cancel the request by simply `unsubscribe` from the returned observable:
883
+
884
+ ```js
885
+ const subscription = client.observable.fetch('*[_type == "movie"]').subscribe((result) => {
886
+ /* do something with the result */
887
+ })
888
+
889
+ // this will cancel the request
890
+ subscription.unsubscribe()
891
+ ```
892
+
849
893
  ### Get client configuration
850
894
 
851
895
  ```js
@@ -882,15 +926,15 @@ MIT © [Sanity.io](https://www.sanity.io/)
882
926
 
883
927
  ## From `v4`
884
928
 
885
- ### No longer shipping `ES5`<!-- omit in toc -->
929
+ ### No longer shipping `ES5`
886
930
 
887
931
  The target is changed to [modern browsers] that supports `ES6` `class`, `{...rest}` syntax and more. You may need to update your bundler to a recent major version. Or you could configure your bundler to transpile `@sanity/client`, and `get-it`, which is the engine that powers `@sanity/client` and uses the same output target.
888
932
 
889
- ### Node.js `v12` no longer supported<!-- omit in toc -->
933
+ ### Node.js `v12` no longer supported
890
934
 
891
935
  Upgrade to the [LTS release, or one of the Maintenance releases](https://github.com/nodejs/release#release-schedule).
892
936
 
893
- ### The `default` export is replaced with the named export `createClient`<!-- omit in toc -->
937
+ ### The `default` export is replaced with the named export `createClient`
894
938
 
895
939
  Before:
896
940
 
@@ -911,7 +955,7 @@ import {createClient} from '@sanity/client'
911
955
  const client = createClient()
912
956
  ```
913
957
 
914
- ### `client.assets.delete` is removed<!-- omit in toc -->
958
+ ### `client.assets.delete` is removed
915
959
 
916
960
  Before:
917
961
 
@@ -927,7 +971,7 @@ After:
927
971
  client.delete('image-abc123_foobar-123x123-png')
928
972
  ```
929
973
 
930
- ### `client.assets.getImageUrl` is removed, replace with [`@sanity/image-url`](https://github.com/sanity-io/image-url)<!-- omit in toc -->
974
+ ### `client.assets.getImageUrl` is removed, replace with [`@sanity/image-url`](https://github.com/sanity-io/image-url)
931
975
 
932
976
  Before:
933
977
 
@@ -958,7 +1002,7 @@ urlFor({_ref: 'image-abc123_foobar-123x123-png'}).url()
958
1002
  urlFor({_ref: 'image-abc123_foobar-123x123-png'}).auto('format').url()
959
1003
  ```
960
1004
 
961
- ### `SanityClient` static properties moved to named exports<!-- omit in toc -->
1005
+ ### `SanityClient` static properties moved to named exports
962
1006
 
963
1007
  Before:
964
1008
 
@@ -974,7 +1018,7 @@ After:
974
1018
  import {Patch, Transaction, ClientError, ServerError, requester} from '@sanity/client'
975
1019
  ```
976
1020
 
977
- ### `client.clientConfig` is removed, replace with `client.config()`<!-- omit in toc -->
1021
+ ### `client.clientConfig` is removed, replace with `client.config()`
978
1022
 
979
1023
  Before:
980
1024
 
@@ -994,64 +1038,7 @@ const client = createClient()
994
1038
  console.log(client.config().projectId)
995
1039
  ```
996
1040
 
997
- ### `client.getUrl()` is removed<!-- omit in toc -->
998
-
999
- Before:
1000
-
1001
- ```ts
1002
- import createClient from '@sanity/client'
1003
- const client = createClient({projectId: 'abc123'})
1004
-
1005
- console.log(client.getUrl('/foo/bar') === 'https://abc123.api.sanity.io/v1/foo/bar')
1006
- console.log(client.getUrl('/foo/bar', true) === 'https://abc123.apicdn.sanity.io/v1/foo/bar')
1007
- ```
1008
-
1009
- After:
1010
-
1011
- ```ts
1012
- import {createClient} from '@sanity/client'
1013
- const client = createClient({projectId: 'abc123'})
1014
-
1015
- const getUrl = (uri: string, useCdn = false) => {
1016
- const config = client.config()
1017
- const base = useCdn ? config.cdnUrl : config.url
1018
- return `${base}/${uri.replace(/^\//, '')}`
1019
- }
1020
-
1021
- console.log(getUrl('/foo/bar') === 'https://abc123.api.sanity.io/v1/foo/bar')
1022
- console.log(getUrl('/foo/bar', true) === 'https://abc123.apicdn.sanity.io/v1/foo/bar')
1023
- ```
1024
-
1025
- ### `client.getDataUrl()` is removed<!-- omit in toc -->
1026
-
1027
- Before:
1028
-
1029
- ```ts
1030
- import createClient from '@sanity/client'
1031
- const client = createClient({dataset: 'bikeshop'})
1032
-
1033
- console.log(client.getDataUrl('doc') === '/data/doc/bikeshop')
1034
- console.log(client.getDataUrl('doc', 'bike-123') === '/data/doc/bikeshop/bike-123')
1035
- ```
1036
-
1037
- After:
1038
-
1039
- ```ts
1040
- import {createClient} from '@sanity/client'
1041
- const client = createClient({dataset: 'bikeshop'})
1042
-
1043
- const getDataUrl = (operation: string, path?: string) => {
1044
- const {dataset} = client.config()
1045
- const baseUri = `/${operation}/${dataset}`
1046
- const uri = path ? `${baseUri}/${path}` : baseUri
1047
- return `/data${uri}`.replace(/\/($|\?)/, '$1')
1048
- }
1049
-
1050
- console.log(getDataUrl('doc') === '/data/doc/bikeshop')
1051
- console.log(getDataUrl('doc', 'bike-123') === '/data/doc/bikeshop/bike-123')
1052
- ```
1053
-
1054
- ### `client.isPromiseAPI()` is removed, replace with an `instanceof` check<!-- omit in toc -->
1041
+ ### `client.isPromiseAPI()` is removed, replace with an `instanceof` check
1055
1042
 
1056
1043
  Before:
1057
1044
 
@@ -1073,7 +1060,7 @@ const client = createClient()
1073
1060
  console.log(client instanceof SanityClient)
1074
1061
  ```
1075
1062
 
1076
- ### `client.observable.isObservableAPI()` is removed, replace with an `instanceof` check<!-- omit in toc -->
1063
+ ### `client.observable.isObservableAPI()` is removed, replace with an `instanceof` check
1077
1064
 
1078
1065
  Before:
1079
1066
 
@@ -1093,7 +1080,7 @@ const client = createClient()
1093
1080
  console.log(client.observable instanceof ObservableSanityClient)
1094
1081
  ```
1095
1082
 
1096
- ### `client._requestObservable` is removed, replace with `client.observable.request`<!-- omit in toc -->
1083
+ ### `client._requestObservable` is removed, replace with `client.observable.request`
1097
1084
 
1098
1085
  Before:
1099
1086
 
@@ -1113,7 +1100,7 @@ const client = createClient()
1113
1100
  client.observable.request({uri: '/ping'}).subscribe()
1114
1101
  ```
1115
1102
 
1116
- ### `client._dataRequest` is removed, replace with `client.dataRequest`<!-- omit in toc -->
1103
+ ### `client._dataRequest` is removed, replace with `client.dataRequest`
1117
1104
 
1118
1105
  Before:
1119
1106
 
@@ -1133,7 +1120,7 @@ const client = createClient()
1133
1120
  client.dataRequest(endpoint, body, options)
1134
1121
  ```
1135
1122
 
1136
- ### `client._create_` is removed, replace with one of `client.create`, `client.createIfNotExists` or `client.createOrReplace`<!-- omit in toc -->
1123
+ ### `client._create_` is removed, replace with one of `client.create`, `client.createIfNotExists` or `client.createOrReplace`
1137
1124
 
1138
1125
  Before:
1139
1126
 
@@ -1157,7 +1144,7 @@ client.createIfNotExists(doc, options)
1157
1144
  client.createOrReplace(doc, options)
1158
1145
  ```
1159
1146
 
1160
- ### `client.patch.replace` is removed, replace with `client.createOrReplace`<!-- omit in toc -->
1147
+ ### `client.patch.replace` is removed, replace with `client.createOrReplace`
1161
1148
 
1162
1149
  Before:
1163
1150
 
@@ -1182,7 +1169,7 @@ client.createOrReplace({
1182
1169
  })
1183
1170
  ```
1184
1171
 
1185
- ### `client.auth` is removed, replace with `client.request`<!-- omit in toc -->
1172
+ ### `client.auth` is removed, replace with `client.request`
1186
1173
 
1187
1174
  Before:
1188
1175
 
@@ -1234,3 +1221,5 @@ await client.request<void>({uri: '/auth/logout', method: 'POST'})
1234
1221
  [api-versioning]: http://sanity.io/docs/api-versioning
1235
1222
  [zod]: https://zod.dev/
1236
1223
  [groqd]: https://github.com/FormidableLabs/groqd#readme
1224
+ [AbortSignal]: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
1225
+ [AbortController]: https://developer.mozilla.org/en-US/docs/Web/API/AbortController
@@ -749,7 +749,8 @@ function _dataRequest(client, httpRequest, endpoint, body) {
749
749
  headers,
750
750
  token,
751
751
  tag,
752
- canUseCdn: isQuery
752
+ canUseCdn: isQuery,
753
+ signal: options.signal
753
754
  };
754
755
  return _requestObservable(client, httpRequest, reqOptions).pipe(operators.filter(isResponse), operators.map(getBody), operators.map(res => {
755
756
  if (!isMutation) {
@@ -796,9 +797,10 @@ function _requestObservable(client, httpRequest, options) {
796
797
  const reqOptions = getRequestOptions(config, Object.assign({}, options, {
797
798
  url: _getUrl(client, uri, useCdn)
798
799
  }));
799
- return new rxjs.Observable(subscriber =>
800
+ const request = new rxjs.Observable(subscriber =>
800
801
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- the typings thinks it's optional because it's not required to specify it when calling createClient, but it's always defined in practice since SanityClient provides a default
801
802
  httpRequest(reqOptions, config.requester).subscribe(subscriber));
803
+ return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
802
804
  }
803
805
  function _request(client, httpRequest, options) {
804
806
  const observable = _requestObservable(client, httpRequest, options).pipe(operators.filter(event => event.type === "response"), operators.map(event => event.body));
@@ -820,6 +822,33 @@ function _getUrl(client, uri) {
820
822
  const base = canUseCdn ? cdnUrl : url;
821
823
  return "".concat(base, "/").concat(uri.replace(/^\//, ""));
822
824
  }
825
+ function _withAbortSignal(signal) {
826
+ return input => {
827
+ return new rxjs.Observable(observer => {
828
+ const abort = () => observer.error(_createAbortError(signal));
829
+ if (signal && signal.aborted) {
830
+ abort();
831
+ return;
832
+ }
833
+ const subscription = input.subscribe(observer);
834
+ signal.addEventListener("abort", abort);
835
+ return () => {
836
+ signal.removeEventListener("abort", abort);
837
+ subscription.unsubscribe();
838
+ };
839
+ });
840
+ };
841
+ }
842
+ const isDomExceptionSupported = Boolean(globalThis.DOMException);
843
+ function _createAbortError(signal) {
844
+ var _a, _b;
845
+ if (isDomExceptionSupported) {
846
+ return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
847
+ }
848
+ const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
849
+ error.name = "AbortError";
850
+ return error;
851
+ }
823
852
  var __accessCheck$4 = (obj, member, msg) => {
824
853
  if (!member.has(obj)) throw TypeError("Cannot " + msg);
825
854
  };
@@ -1525,6 +1554,24 @@ const _ObservableSanityClient = class {
1525
1554
  request(options) {
1526
1555
  return _request(this, __privateGet(this, _httpRequest), options);
1527
1556
  }
1557
+ /**
1558
+ * Get a Sanity API URL for the URI provided
1559
+ *
1560
+ * @param uri - URI/path to build URL for
1561
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1562
+ */
1563
+ getUrl(uri, canUseCdn) {
1564
+ return _getUrl(this, uri, canUseCdn);
1565
+ }
1566
+ /**
1567
+ * Get a Sanity API URL for the data operation and path provided
1568
+ *
1569
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1570
+ * @param path - Path to append after the operation
1571
+ */
1572
+ getDataUrl(operation, path) {
1573
+ return _getDataUrl(this, operation, path);
1574
+ }
1528
1575
  };
1529
1576
  let ObservableSanityClient = _ObservableSanityClient;
1530
1577
  _clientConfig = new WeakMap();
@@ -1658,10 +1705,31 @@ const _SanityClient = class {
1658
1705
  dataRequest(endpoint, body, options) {
1659
1706
  return rxjs.lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
1660
1707
  }
1708
+ /**
1709
+ * Get a Sanity API URL for the URI provided
1710
+ *
1711
+ * @param uri - URI/path to build URL for
1712
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1713
+ */
1714
+ getUrl(uri, canUseCdn) {
1715
+ return _getUrl(this, uri, canUseCdn);
1716
+ }
1717
+ /**
1718
+ * Get a Sanity API URL for the data operation and path provided
1719
+ *
1720
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1721
+ * @param path - Path to append after the operation
1722
+ */
1723
+ getDataUrl(operation, path) {
1724
+ return _getDataUrl(this, operation, path);
1725
+ }
1661
1726
  };
1662
1727
  let SanityClient = _SanityClient;
1663
1728
  _clientConfig2 = new WeakMap();
1664
1729
  _httpRequest2 = new WeakMap();
1730
+ function migrationNotice() {
1731
+ throw new TypeError("The default export of @sanity/client has been deprecated. Use the named export `createClient` instead");
1732
+ }
1665
1733
  const httpRequest = defineHttpRequest(envMiddleware);
1666
1734
  const requester = httpRequest.defaultRequester;
1667
1735
  const createClient = config => new SanityClient(httpRequest, config);
@@ -1676,5 +1744,6 @@ exports.SanityClient = SanityClient;
1676
1744
  exports.ServerError = ServerError;
1677
1745
  exports.Transaction = Transaction;
1678
1746
  exports.createClient = createClient;
1747
+ exports.default = migrationNotice;
1679
1748
  exports.requester = requester;
1680
1749
  //# sourceMappingURL=index.browser.cjs.map