@sanity/client
Javascript client for Sanity. Works in node.js and modern browsers (older browsers needs a Promise polyfill).
Requirements
Sanity Client requires the JavaScript runtime to have a global ES6-compliant Promise
available. If your runtime environment doesn't provide a spec compliant Promise
implementation, we recommend using native-promise-only, es6-promise or another spec-compliant implementation. See this article for more information.
Installation
The client can be installed from npm:
npm install --save @sanity/client
API
const sanityClient = const client =
const client = sanityClient(options)
Initializes a new Sanity Client. Required options are projectId
and dataset
.
Performing queries
const query = '*[_type == "bike" && seats >= $minSeats] {name, seats}'const params = minSeats: 2 client
client.fetch(query, params = {})
Perform a query using the given parameters (if any).
Listening to queries
const query = '*[_type == "comment" && authorId != $ownerId]'const params = ownerId: 'bikeOwnerUserId' const subscription = client // to unsubscribe later onsubscription
client.listen(query, params = {}, options = {includeResult: true})
Open a query that listens for updates on matched documents, using the given parameters (if any). The return value is an RxJS Observable. When calling .subscribe()
on the returned observable, a subscription is returned, and this can be used to unsubscribe from the query later on by calling subscription.unsubscribe()
The update events which are emitted always contain mutation
, which is an object containing the mutation which triggered the document to appear as part of the query.
By default, the emitted update event will also contain a result
property, which contains the document with the mutation applied to it. In case of a delete mutation, this property will not be present, however. You can also tell the client not to return the document (to save bandwidth, or in cases where the mutation or the document ID is the only relevant factor) by setting the includeResult
property to false
in the options.
Likewise, you can also have the client return the document before the mutation was applied, by settingincludePreviousRevision
to true
in the options, which will include a previous
property in each emitted object.
Fetch a single document
This will fetch a document from the DOC endpoint. Should be used sparingly and performing a query is usually a better option.
client
Fetch multiple documents in one go
This will fetch multiple documents in one request from the DOC endpoint. Should be used sparingly and performing a query is usually a better option.
client
Note: Unlike in the HTTP API, the order/position of documents is preserved based on the original array of IDs. If a any of the documents are missing, they will be replaced by a null
entry in the returned array:
const ids = 'bike123' 'nonexistent-document' 'bike345'client
Creating documents
const doc = _type: 'bike' name: 'Sanity Tandem Extraordinaire' seats: 2 client
client.create(doc)
Create a document. Argument is a plain JS object representing the document. It must contain a _type
attribute. It may contain an _id
. If an ID is not specified, it will automatically be created.
Creating/replacing documents
const doc = _id: 'my-bike' _type: 'bike' name: 'Sanity Tandem Extraordinaire' seats: 2 client
client.createOrReplace(doc)
If you are not sure whether or not a document exists but want to overwrite it if it does, you can use the createOrReplace()
method. When using this method, the document must contain an _id
attribute.
Creating if not already present
const doc = _id: 'my-bike' _type: 'bike' name: 'Sanity Tandem Extraordinaire' seats: 2 client
client.createIfNotExists(doc)
If you want to create a document if it does not already exist, but fall back without error if it does, you can use the createIfNotExists()
method. When using this method, the document must contain an _id
attribute.
Patch/update a document
client // Document ID to patch // Shallow merge // Increment field by count // Perform the patch and return a promise
Modify a document. patch
takes a document ID. set
merges the partialDoc with the stored document. inc
increments the given field with the given numeric value. commit
executes the given patch
. Returns the updated object.
Setting a field only if not already present
client
Removing/unsetting fields
client
Incrementing/decrementing numbers
client // Increment `price` by 88, `numSales` by 1 // Decrement `inStock` by 1
Patch a document only if revision matches
You can use the ifRevisionId(rev)
method to specify that you only want the patch to be applied if the stored document matches a given revision.
client
Adding elements to an array
The patch operation insert
takes a location (before
, after
or replace
), a path selector and an array of elements to insert.
const nanoid = client // Ensure that the `reviews` arrays exists before attempting to add items to it // Add the items after the last item in the array (append)
Appending/prepending elements to an array
The operations of appending and prepending to an array are so common that they have been given their own methods for better readability:
const nanoid = client
Deleting an element from an array
Each entry in the unset
array can be either an attribute or a JSON path.
In this example, we remove the first review and the review with _key: 'abc123'
from the bike.reviews
array:
const reviewsToRemove = 'reviews[0]' 'reviews[_key=="abc123"]'client
Delete a document
client
client.delete(docId)
Delete a document. Parameter is a document ID.
Multiple mutations in a transaction
const namePatch = client client
client.transaction().create(doc).delete(docId).patch(patch).commit()
Create a transaction to perform chained mutations.
client
client.transaction().create(doc).patch(docId, p => p.set(partialDoc)).commit()
A patch
can be performed inline on a transaction
.
Clientless patches & transactions
Transactions and patches can also be built outside the scope of a client:
const sanityClient = const client = // Patches:const patch = '<documentId>'client // Transactions:const transaction = client
const patch = new sanityClient.Patch(docId)
const transaction = new sanityClient.Transaction()
An important note on this approach is that you cannot call commit()
on transactions or patches instantiated this way, instead you have to pass them to client.mutate()
Uploading assets
Assets can be uploaded using the client.assets.upload(...)
method.
client.asset.upload(type: 'file' | image', body: File | Blob | Buffer | NodeStream, options = {}): Promise<AssetDocument>
👉 Read more about assets in Sanity
Examples: Uploading assets from Node.js
// Upload a file from the file systemclientassets
// Upload an image file from the file systemclientassets
Examples: Uploading assets from the Browser
// Create a file with "foo" as its contentconst file = 'foo' 'foo.txt' type: 'text/plain'// Upload itclientassets
// Draw something on a canvas and upload as imageconst canvas = documentconst ctx = canvasctxfillStyle = '#f85040'ctxctxfillStyle = '#fff'ctxfont = '10px monospace'ctxcanvas { clientassets }
Examples: Specify image metadata to extract
// Extract palette of colors as well as GPS location from exifclientassets
Deleting an asset
Deleting an asset document will also trigger deletion of the actual asset.
client.delete(id: string): Promise
client
Get client configuration
const config = clientconsole
client.config()
Get client configuration.
Set client configuration
client
client.config(options)
Set client configuration. Required options are projectId
and dataset
.