Sanity HTTP API: How to add an array of references? - sanity

What is the correct way to add an array of references using the Sanity HTTP API?
I'm able to add a single reference:
const mutations = [{
createOrReplace: {
_id: '123',
_type: 'cms.article',
title: 'An article',
author: {
_ref: '12f90f00-8cfb-4161-8bea-26180',
_type: 'reference'
},
}
}]
I expected adding an array of references to existing tags would work (it returns with Status 200)
const mutations = [{
createOrReplace: {
_id: '123',
_type: 'cms.article',
title: 'An article',
author: {
_ref: '12f90f00-8cfb-4161-8bea-26180',
_type: 'reference'
},
tags: [
{
_ref: 'foo',
_type: 'reference'
},
{
_ref: 'bar',
_type: 'reference'
},
]
}
}]
But Sanity Studio crashes with Error: Unsupported path segment {} when I attempt to view the document.

It may help to break this down:
First, a reference is an object that contains a _type and a _ref. The _type will always be 'reference' and the _ref will always be the _id of the document you're referencing.
Second, an array can be either an array of strings or of objects. Either way, any item in an array needs a unique _key.
So, putting all of that together, your mutation would look like this:
field: [
{
_key: '<some-uuid>'
_ref: '<_id-of-document>',
_type: 'reference'
},
]
When it comes to generating keys, you can use an external package (uuid is common) or if you're using the JS client auto generate keys by passing { autoGenerateArrayKeys: true } to your commit().

Related

Display all properties of an array of objects in Sanity.io

In a Sanity project, I've created a schema containing an array of objects.
In Sanity Studio, this appears as a list of those objects' first property, but I really need to see at least 2 properties for it to be meaningful.
I can't find a way to do this. Is it possible?
Below is my schema. It represents a blog article which holds an array of translations. Each translation is defined by a language and a reference to another article.
// sanity\schemas\documents\article.ts
import { defineArrayMember, defineField, defineType } from "sanity"
import translation from "../objects/translation";
export default defineType({
title: 'Article',
name: 'article',
type: 'document',
fields: [
defineField({ title: 'Title', name: 'title', type: 'string' }),
defineField({ title: 'Translations', name: 'translations', type: 'array', of: [defineArrayMember(translation)] }),
// sanity\schemas\objects\translation.ts
import { defineField, defineType } from "sanity"
export default defineType({
title: 'Translation',
name: 'translation',
type: 'object',
fields: [
defineField({ title: 'Language', name: 'language', type: 'string' }),
defineField({ title: 'Article', name: 'article', type: 'reference', to: [{ type: 'article' }] }),
]
});
This is how it shows up:
I would like to see "fr - title of the article in french".
Note that I'd like to do this for other fields too, so I'm not looking for a package to handle internationalisation. Is it doable?
Found the answer: sanity.io/docs/previews-list-views
I hadn't realised this applies to lists within fields too, not just lists of documents. Adding the "preview" property at the root of my schema did the trick:
preview: {
select: {
title: 'field1',
subtitle: 'field2'
}
}

Indexes: Search by Boolean?

I'm having some trouble with FaunaDB Indexes. FQL is quite powerful but the docs seem to be limited (for now) to only a few examples/use cases. (Searching by String)
I have a collection of Orders, with a few fields: status, id, client, material and date.
My goal is to search/filter for orders depending on their Status, OPEN OR CLOSED (Boolean true/false).
Here is the Index I created:
CreateIndex({
name: "orders_all_by_open_asc",
unique: false,
serialized: true,
source: Collection("orders"),
terms: [{ field: ["data", "status"] }],
values: [
{ field: ["data", "unique_id"] },
{ field: ["data", "client"] },
{ field: ["data", "material"] },
{ field: ["data", "date"] }
]
}
So with this Index, I want to specify either TRUE or FALSE and get all corresponding orders, including their data (fields).
I'm having two problems:
When I pass TRUE OR FALSE using the Javascript Driver, nothing is returned :( Is it possible to search by Booleans at all, or only by String/Number?
Here is my Query (in FQL, using the Shell):
Match(Index("orders_all_by_open_asc"), true)
And unfortunately, nothing is returned. I'm probably doing this wrong.
Second (slightly unrelated) question. When I create an Index and specify a bunch of Values, it seems the data returned is in Array format, with only the values, not the Fields. An example:
[
1001,
"client1",
"concrete",
"2021-04-13T00:00:00.000Z",
],
[
1002,
"client2",
"wood",
"2021-04-13T00:00:00.000Z",
]
This format is bad for me, because my front-end expects receiving an Object with the Fields as a key and the Values as properties. Example:
data:
{
unique_id : 1001,
client : "client1",
material : "concrete",
date: "2021-04-13T00:00:00.000Z"
},
{
unique_id : 1002,
client : "client2",
material : "wood",
date: "2021-04-13T00:00:00.000Z"
},
etc..
Is there any way to get the Field as well as the Value when using Index values, or will it always return an Array (and not an object)?
Could I use a Lambda or something for this?
I do have another Query that uses Map and Lambda to good effect, and returns the entire document, including the Ref and Data fields:
Map(
Paginate(
Match(Index("orders_by_date"), date),
),
Lambda('item', Get(Var('item')))
)
This works very nicely but unfortunately, it also performs one Get request per Document returned and that seems very inefficient.
This new Index I'm wanting to build, to filter by Order Status, will be used to return hundreds of Orders, hundreds of times a day. So I'm trying to keep it as efficient as possible, but if it can only return an Array it won't be useful.
Thanks in advance!! Indexes are great but hard to grasp, so any insight will be appreciated.
You didn't show us exactly what you have done, so here's an example that shows that filtering on boolean values does work using the index you created as-is:
> CreateCollection({ name: "orders" })
{
ref: Collection("orders"),
ts: 1618350087320000,
history_days: 30,
name: 'orders'
}
> Create(Collection("orders"), { data: {
unique_id: 1,
client: "me",
material: "stone",
date: Now(),
status: true
}})
{
ref: Ref(Collection("orders"), "295794155241603584"),
ts: 1618350138800000,
data: {
unique_id: 1,
client: 'me',
material: 'stone',
date: Time("2021-04-13T21:42:18.784Z"),
status: true
}
}
> Create(Collection("orders"), { data: {
unique_id: 2,
client: "you",
material: "muslin",
date: Now(),
status: false
}})
{
ref: Ref(Collection("orders"), "295794180038328832"),
ts: 1618350162440000,
data: {
unique_id: 2,
client: 'you',
material: 'muslin',
date: Time("2021-04-13T21:42:42.437Z"),
status: false
}
}
> CreateIndex({
name: "orders_all_by_open_asc",
unique: false,
serialized: true,
source: Collection("orders"),
terms: [{ field: ["data", "status"] }],
values: [
{ field: ["data", "unique_id"] },
{ field: ["data", "client"] },
{ field: ["data", "material"] },
{ field: ["data", "date"] }
]
})
{
ref: Index("orders_all_by_open_asc"),
ts: 1618350185940000,
active: true,
serialized: true,
name: 'orders_all_by_open_asc',
unique: false,
source: Collection("orders"),
terms: [ { field: [ 'data', 'status' ] } ],
values: [
{ field: [ 'data', 'unique_id' ] },
{ field: [ 'data', 'client' ] },
{ field: [ 'data', 'material' ] },
{ field: [ 'data', 'date' ] }
],
partitions: 1
}
> Paginate(Match(Index("orders_all_by_open_asc"), true))
{ data: [ [ 1, 'me', 'stone', Time("2021-04-13T21:42:18.784Z") ] ] }
> Paginate(Match(Index("orders_all_by_open_asc"), false))
{ data: [ [ 2, 'you', 'muslin', Time("2021-04-13T21:42:42.437Z") ] ] }
It's a little more work, but you can compose whatever return format that you like:
> Map(
Paginate(Match(Index("orders_all_by_open_asc"), false)),
Lambda(
["unique_id", "client", "material", "date"],
{
unique_id: Var("unique_id"),
client: Var("client"),
material: Var("material"),
date: Var("date"),
}
)
)
{
data: [
{
unique_id: 2,
client: 'you',
material: 'muslin',
date: Time("2021-04-13T21:42:42.437Z")
}
]
}
It's still an array of results, but each result is now an object with the appropriate field names.
Not too familiar with FQL, but I am somewhat familiar with SQL languages. Essentially, database languages usually treat all of your values as strings until they don't need to anymore. Instead, your query should use the string definition that FQL is expecting. I believe it should be OPEN or CLOSED in your case. You can simply have an if statement in java to determine whether to search for "OPEN" or "CLOSED".
To answer your second question, I don't know for FQL, but if that is what is returned, then your approach with a lamda seems to be fine. Not much else you can do about it from your end other than hope that you get a different way to get entries in API form somewhere in the future. At the end of the day, an O(n) operation in this context is not too bad, and only having to return a hundred or so orders shouldn't be the most painful thing in the world.
If you are truly worried about this, you can break up the request into portions, so you return only the first 100, then when frontend wants the next set, you send the next 100. You can cache the results too to make it very fast from the front-end perspective.
Another suggestion, maybe I am wrong and failed at searching the docs, but I will post anyway just in case it's helpful.
My index was failing to return objects, example data here is the client field:
"data": {
"status": "LIVRAISON",
"open": true,
"unique_id": 1001,
"client": {
"name": "TEST1",
"contact_name": "Bob",
"email": "bob#client.com",
"phone": "555-555-5555"
Here, the client field returned as null even though it was specified in the Index.
From reading the docs, here: https://docs.fauna.com/fauna/current/api/fql/indexes?lang=javascript#value
In the Value Objects section, I was able to understand that for Objects, the Index Field must be defined as an Array, one for each Object key. Example for my data:
{ field: ['data', 'client', 'name'] },
{ field: ['data', 'client', 'contact_name'] },
{ field: ['data', 'client', 'email'] },
{ field: ['data', 'client', 'phone'] },
This was slightly confusing, because my beginner brain expected that defining the 'client' field would simply return the entire object, like so:
{ field: ['data', 'client'] },
The only part about this in the docs was this sentence: The field ["data", "address", "street"] refers to the street field contained in an address object within the document’s data object.
This is enough information, but maybe it would deserve its own section, with a longer example? Of course the simple sentence works, but with a sub-section called 'Adding Objects to Fields' or something, this would make it extra-clear.
Hoping my moments of confusion will help out. Loving FaunaDB so far, keep up the great work :)

How do I access an asset's URL when linked via reference in Sanity Studio?

I want to upload PDFs in Sanity Studio, then link to those PDFs in the main site content.
I've added a reference to a document which has a 'file' field in it to my simpleBlockContent input in Sanity Studio.
I've created a document schema for the PDF:
export default {
title: "PDF Upload",
name: "pdfDocument",
type: "document",
fields: [
{
name: "title",
type: "string",
title: "Title",
description: "This title will be used as a caption for the download.",
},
{
name: "pdfFile",
type: "file",
title: "PDF File",
options: {
accept: ".pdf",
},
validation: (Rule) => Rule.required(),
description: "Note that the file name will be visible to end users downloading the file.",
},
],
};
And I'm attempting to reference it in my input component's schema:
export default {
title: "Simple Block Content",
name: "simpleBlockContent",
type: "array",
of: [
{
title: "Block",
type: "block",
styles: [],
marks: {
annotations: [
{
name: "pdfLink",
type: "object",
title: "PDF download link",
fields: [
{
name: "pdfReference",
type: "reference",
title: "PDF Document",
to: [{ type: "pdfDocument" }],
},
],
},
],
},
},
],
};
However when I add pdfLink to my serializers.js in the frontend, nothing resembling a link to the file is present in the data passed to it from my _rawContent graphql query that handles all other page content.
How can I access the information needed to build a URL that links to the uploaded asset?
I've yet to do this in a serializer, but it looks as though the asset URL should be accessible in the returned document, according to the docs:
Example of returned asset document:
{
"_id": "image-abc123_0G0Pkg3JLakKCLrF1podAdE9-538x538-jpg",
"_type": "sanity.imageAsset", // type is prefixed by sanity schema
"assetId": "0G0Pkg3JLakKCLrF1podAdE9",
"path": "images/myproject/mydataset/abc123_0G0Pkg3JLakKCLrF1podAdE9-538x538.jpg",
"url": "https://cdn.sanity.io/images/myproject/mydataset/abc123_0G0Pkg3JLakKCLrF1podAdE9-538x538.jpg",
"originalFilename": "bicycle.jpg",
"size": 2097152, // File size, in bytes
"metadata": {
"dimensions": {
"height": 538,
"width": 538,
"aspectRatio": 1.0
},
"location":{ // only present if the original image contained location metadata
"lat": 59.9241370,
"lon": 10.7583846,
"alt": 21.0
}
}
}
I was looking for a way to get instant link in sanity studio when someone upload file in sanity and couldn't find any good solution so I came up with my own
Problem
let people upload files to sanity and get instant link that they can copy and paste in blog, case study etc
Solution
use slug as in option you have acces to doc where you can generate link my code
import { tryGetFile } from '#sanity/asset-utils'; // this function creates production link
const pdfUploader = {
name: 'pdfUploader',
title: 'Upload PDF and Get Link',
type: 'document',
preview: {
select: {
title: 'title',
},
},
fields: [
{
name: 'title',
title: 'Title',
description: 'Name displayed on pdf list',
type: 'string',
validation: (Rule) => [Rule.required()],
},
{
name: 'pdfFile',
title: 'Upload PDF File',
description: 'PDF File you want to upload, once you upload click generate URL',
type: 'file',
validation: (Rule) => [Rule.required()],
},
{
name: 'generatedPDFURL',
title: 'Generate URL Link to this pdf',
description:
'Click GENERATE to get Link to pdf file, if you by mistake change it, click generate again. Then Copy link below and paste it anywhere you want',
type: 'slug',
options: {
// this source takes all data that is currently in this document and pass it as argument
// then tryGetFile() - getting file from sanity with all atributes like url, original name etc
source: ({ pdfFile }) => {
if (!pdfFile) return 'Missing PDF File';
const { asset } = tryGetFile(pdfFile?.asset?._ref, {
// put your own envs
dataset: process.env.SANITY_DATASET,
projectId: process.env.SANITY_PROJECT_ID,
});
return asset?.url;
},
// this slugify prevent from changing "/" to "-" it keeps the original link and prevent from slugifying
slugify: (link) => link,
},
validation: (Rule) => [Rule.required()],
},
],
};
export default pdfUploader;
After this in sanity upload file and then click GENERATE to get link
Hope it helps people who are looking for similar solution, slug is not perfect choice but it's working :)

Resolve reference in Block Content in Sanity.io

I have the Content Block in Sanity like so:
export default {
title: "Block Content",
name: "blockContent",
type: "array",
of: [
/// stuff here
{
title: "Book",
type: "reference",
to: [{ type: "book" }],
},
],
};
When making a query like
'*[_type == "post"]{...,body[]{..., asset->{..., "_key": _id}, markDefs[]{..., _type == "internaLink" => {"slug": #.reference->slug}}}';
I get the reference, but I want to return the full Document. I tried every method but the documentation only explain references outside Content Blocks and those methods aren't working.
This is what's returned from the Query:
_createdAt: '2020-12-07T14:43:34Z',
_id: '9d628aa6-aba7-4b53-aa9f-c6e97583baf9',
_rev: 'ZZ0GkIKCRvD0tdMQPywPfl',
_type: 'post',
_updatedAt: '2020-12-07T14:43:34Z',
body: [
{
_key: '4184df372bae',
_type: 'block',
children: [Array],
markDefs: [],
style: 'normal'
},
{
_key: '56bed8835a7d',
_ref: 'dc2eefee-2200-43e1-99c7-ea989dda16ba',
_type: 'reference'
}
],
title: 'Example'
Solved, I'm writing the solution here as I found nothing on the web.
Basically I tried anything randomly until I got the desired result.
The query is:
_type=="reference"=>^->
I had a similar situation where I had was grabbing a story object that had a body which was a blockContent, and I had just added a blog reference as a block option to the body.
I solved it by using this query:
const query = groq`*[_type == "story" && slug.current == $slug][0]{
title,
description,
body[]{
_type == 'blog' => #->,
_type != 'blog' => #,
}
}`
It loops through all the array items inside of the body and if a specific one is a blog, then it dereferences it by using ->, otherwise it outputs the already existing value.

Using if/then/else schema validation conditional on values in other json objects

I'm trying to use if/then/else to use three different schemas for an object, but based on the value of a JSON field outside of that object. I've only seen example of people making their conditionals based on fields within the same object.
Here's what I've tried:
schema: {
'MyOtherObject': {
'$id': '#/properties/MyOtherObject',
'type': 'object',
'additionalProperties': false,
'title': 'The MyOtherObject Schema',
'required': [
'PaymentMethod'
],
'properties': {
'PaymentMethod': {
'$id': '#/properties/Deal/properties/PaymentMethod',
'type': 'string',
'title': 'The PaymentMethod Schema',
'default': '',
'examples': [
'Cash'
],
'pattern': '^(.*)$'
},
...
},
'MyConditionalSchemaObject': {
'$id': '#/properties/MyConditionalSchemaObject',
'type': 'object',
'additionalProperties': false,
'title': 'The MyConditionalSchemaObject Schema',
'if': {
// Trying to get at the value above but don't know how... my schema validations still failing
'2/MyOtherObject/properties/PaymentMethod' : { 'const': 'Cash' }
},
'then': {
'required': [
'PaymentStartDate'
],
'properties': {
'BankName': {
'$id': '#/properties/Financing/properties/BankName',
'type': ['string', 'null'],
'title': 'The Bankname Schema',
'default': '',
'examples': [
'Capital One Auto Finance'
],
...
}
}
I would expect that this code would check the value of the PaymentMethod field in the MyOtherObject json object and then use the schema based on passing the conditional check (if it equals Cash), but I'm still getting schema validation errors saying, Should not be additional properties 'BankName', implying that the schema in the "then" block is not being used for validation.