Generate Mock Data from Sanity Schemas
npm install sanity @faker-js/faker @sanity-typed/faker
product.ts
:
// import { defineArrayMember, defineField, defineType } from "sanity";
import {
defineArrayMember,
defineField,
defineType,
} from "@sanity-typed/types";
/** No changes using defineType, defineField, and defineArrayMember */
export const product = defineType({
name: "product",
type: "document",
title: "Product",
fields: [
defineField({
name: "productName",
type: "string",
title: "Product name",
validation: (Rule) => Rule.required(),
}),
defineField({
name: "tags",
type: "array",
title: "Tags for item",
of: [
defineArrayMember({
type: "object",
name: "tag",
fields: [
defineField({ type: "string", name: "label" }),
defineField({ type: "string", name: "value" }),
],
}),
],
}),
],
});
sanity.config.ts
:
import { deskTool } from "sanity/desk";
// import { defineConfig } from "sanity";
import { defineConfig } from "@sanity-typed/types";
import type { InferSchemaValues } from "@sanity-typed/types";
import { post } from "./schemas/post";
import { product } from "./schemas/product";
/** No changes using defineConfig */
const config = defineConfig({
projectId: "59t1ed5o",
dataset: "production",
plugins: [deskTool()],
schema: {
types: [
product,
// ...
post,
],
},
});
export default config;
/** Typescript type of all types! */
export type SanityValues = InferSchemaValues<typeof config>;
/**
* SanityValues === {
* product: {
* _createdAt: string;
* _id: string;
* _rev: string;
* _type: "product";
* _updatedAt: string;
* productName: string;
* tags?: {
* _key: string;
* _type: "tag";
* label?: string;
* value?: string;
* }[];
* };
* // ... all your types!
* }
*/
mocks.ts
:
import { base, en } from "@faker-js/faker";
import config from "sanity.config";
import { sanityConfigToFaker, sanityDocumentsFaker } from "@sanity-typed/faker";
export const getMockDataset = () => {
const sanityFaker = sanityConfigToFaker(config, {
faker: { locale: [en, base] },
});
/**
* typeof sanityFaker === {
* [type in keyof SanityValues]: () => SanityValues[type];
* }
*/
const documentsFaker = sanityDocumentsFaker(config, sanityFaker);
/**
* typeof documentsFaker === () => SanityValues[keyof SanityValues][]
*/
return documentsFaker();
};
While sanityConfigToFaker
gives you all the fakers for a given config keyed by type, sometimes you just want an array of all the SanityDocument
s. Drop it into sanityDocumentsFaker
:
import type {
sanityConfigToFaker,
sanityDocumentsFaker,
} from "@sanity-typed/zod";
const config = defineConfig({
/* ... */
});
const fakers = sanityConfigToFaker(config);
/**
* fakers === { [type: string]: () => typeButSomeTypesArentDocuments }
*/
const documentsFaker = sanityDocumentsFaker(config, fakers);
/**
* documentsFaker === () => (Each | Document | In | An | Array | Many | Times)[]
*/
Reference mocks point to document mocks, so you can use groq-js
or @sanity-typed/groq-js
and be certain that your references will work.
This is done in chunks of 5. For example, if foo
has references that point to bar
, you can be assured that the the first five mocks of foo
has references that all refer to the first five mocks of bar
. In other words, if you generate five foo
mocks and five bar
mocks, then all the references will be contained within those documents. If you want to change this number, pass a different referencedChunkSize
to sanityConfigToFaker(config, { faker, referencedChunkSize })
.
The tests for this are a good explanation.
As much as is reasonable, a field's mocked values should stay consistent between runs of your application. This is why the faker
parameter accepts a FakerOptions
rather than a Faker
: each field instantiates it's own Faker
with a seed corresponding to the field's path. This means that, even when you change all the fields or array members around a field, that field will produce the same mocked values, as long as the path to it stays consistent. This becomes especially important when you're using slug
for url paths, since you don't want your urls to change every time you change your schema. However, whenever you update your dependencies, we can't ensure that we generated mocks the same way, so don't be surprised if you see some changes in your mocked data.
The tests for this are a good explanation.
If there are custom mocks you want to include, using customMock
on the schema types includes it:
import { customMock, sanityConfigToFaker } from "@sanity-typed/faker";
import { defineConfig, defineField, defineType } from "@sanity-typed/types";
export const product = defineType({
name: "product",
type: "document",
title: "Product",
fields: [
customMock(
defineField({
name: "productName",
type: "string",
title: "Product name",
}),
// `previous` is what the mocked value would have been, which is helpful
// to have when you only want to override one field in an object
// `index` is the index of the mock overall, helping with the reference validity
// This is helpful if you want to override slugs, eg always having index === 0
// give a locally consistent url
(faker, previous, index) => faker.commerce.productName()
),
// ...
],
});
// Everything else the same as before...
const config = defineConfig({
projectId: "your-project-id",
dataset: "your-dataset-name",
schema: {
types: [
product,
// ...
],
},
});
const sanityFaker = sanityConfigToFaker(config, {
faker: { locale: [en, base] },
});
const mock = sanityFaker.product();
// mock.productName is something like "Computer" rather than the default from "string"
Be aware that, besides typing, no validations or checks are done on the custom mocks. The validity of your custom mocked values are up to you.
@sanity-typed/*
generally has the goal of only having effect to types and no runtime effects. This package is an exception. This means that you will have to import your sanity config to use this. While sanity v3 is better than v2 at having a standard build environment, you will have to handle any nuances, including having a much larger build.
Often you'll run into an issue where you get typescript errors in your IDE but, when building workspace (either you studio or app using types), there are no errors. This only occurs because your IDE is using a different version of typescript than the one in your workspace. A few debugging steps:
- The
JavaScript and TypeScript Nightly
extension (identifierms-vscode.vscode-typescript-next
) creates issues here by design. It will always attempt to use the newest version of typescript instead of your workspace's version. I ended up uninstalling it. -
Check that VSCode is actually using your workspace's version even if you've defined the workspace version in
.vscode/settings.json
. UseTypeScript: Select TypeScript Version
to explictly pick the workspace version. - Open any typescript file and you can see which version is being used in the status bar. Please check this (and provide a screenshot confirming this) before creating an issue. Spending hours debugging your issue ony to find that you're not using your workspace's version is very frustrating.