npm package: @sanity-typed/faker
Description: Generate Mock Data from Sanity Schemas
Latest version: 5.0.1

# @sanity-typed/faker

[![NPM Downloads](https://img.shields.io/npm/dw/@sanity-typed/faker?style=flat&logo=npm)](https://www.npmjs.com/package/@sanity-typed/faker)
[![GitHub commit activity (branch)](https://img.shields.io/github/commit-activity/m/saiichihashimoto/sanity-typed?style=flat&logo=github)](https://github.com/saiichihashimoto/sanity-typed/pulls?q=is%3Apr+is%3Aclosed)
[![GitHub Repo stars](https://img.shields.io/github/stars/saiichihashimoto/sanity-typed?style=flat&logo=github)](https://github.com/saiichihashimoto/sanity-typed/stargazers)
[![GitHub contributors](https://img.shields.io/github/contributors/saiichihashimoto/sanity-typed?style=flat&logo=github)](https://github.com/saiichihashimoto/sanity-typed/graphs/contributors)
[![GitHub issues by-label](https://img.shields.io/github/issues/saiichihashimoto/sanity-typed/help%20wanted?style=flat&logo=github&color=007286)](https://github.com/saiichihashimoto/sanity-typed/labels/help%20wanted)
[![Minified Size](https://img.shields.io/bundlephobia/min/@sanity-typed/faker?style=flat)](https://www.npmjs.com/package/@sanity-typed/faker?activeTab=code)
[![License](https://img.shields.io/github/license/saiichihashimoto/sanity-typed?style=flat)](LICENSE)

[![GitHub Sponsors](https://img.shields.io/github/sponsors/saiichihashimoto?style=flat&logo=githubsponsors)](https://github.com/sponsors/saiichihashimoto)

Generate Mock Data from Sanity Schemas

[![Watch How to Offline Your Sanity Client and Generate Mock Data](https://github.com/saiichihashimoto/sanity-typed/assets/2819256/fc2be145-d504-46e3-9e77-6090c3024885)](https://github.com/saiichihashimoto/sanity-typed/assets/2819256/fed71d58-6b08-467a-a325-b197f563a328)

## Page Contents
- [Install](#install)
- [Usage](#usage)
- [`sanityDocumentsFaker`](#sanitydocumentsfaker)
- [Reference Validity](#reference-validity)
- [Field Consistency](#field-consistency)
- [Custom Mocks](#custom-mocks)
- [Considerations](#considerations)
  - [Config in Runtime](#config-in-runtime)
  - [Typescript Errors in IDEs](#typescript-errors-in-ides)
    - [VSCode](#vscode)
- [Breaking Changes](#breaking-changes)
  - [4 to 5](#4-to-5)
    - [Node Requirement to ^22.14.0](#node-requirement-to-22140)
  - [3 to 4](#3-to-4)
    - [Typescript version from 5.7.2 <= x <= 5.7.3](#typescript-version-from-572--x--573)
  - [2 to 3](#2-to-3)
    - [Typescript version from 5.4.2 <= x <= 5.6.3](#typescript-version-from-542--x--563)

## Install

```bash
npm install sanity @faker-js/faker @sanity-typed/faker
```

## Usage

```product.ts```:
```typescript
// 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```:
```typescript
import { structureTool } from "sanity/structure";

// 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: [structureTool()],
  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```:
```typescript
import { base, en } from "@faker-js/faker";
import config from "sanity.config";

import { sanityConfigToFaker, sanityDocumentsFaker } from "@sanity-typed/faker";

export const getMockDataset = async () => {
  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();
};
```

## `sanityDocumentsFaker`

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`:

```typescript
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 Validity

Reference mocks point to document mocks, so you can use [`groq-js` or `@sanity-typed/groq-js`](../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](./src/document-id-memo.test.ts) are a good explanation.

## Field Consistency

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](https://fakerjs.dev/guide/usage.html#reproducible-results) 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](./src/consistency.test.ts) are a good explanation.

## Custom Mocks

If there are custom mocks you want to include, using `customMock` on the schema types includes it:

```typescript
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.

## Considerations

### Config in Runtime

`@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.
### Typescript Errors in IDEs

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:

#### VSCode

- The [`JavaScript and TypeScript Nightly` extension (identifier `ms-vscode.vscode-typescript-next`)](https://marketplace.visualstudio.com/items?itemName=ms-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](https://code.visualstudio.com/docs/typescript/typescript-compiling#_compiler-versus-language-service) even if you've [defined the workspace version in `.vscode/settings.json`](https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-the-workspace-version-of-typescript). Use `TypeScript: 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](https://code.visualstudio.com/docs/typescript/typescript-compiling#_compiler-versus-language-service). 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.

## Breaking Changes

### 4 to 5

#### Node Requirement to ^22.14.0

The required Node version is now ^22.14.0. Older versions are no longer supported and newer versions will be added as we validate them.

### 3 to 4

#### Typescript version from 5.7.2 <= x <= 5.7.3

The supported Typescript version is now 5.7.2 <= x <= 5.7.3. Older versions are no longer supported and newer versions will be added as we validate them.

### 2 to 3

#### Typescript version from 5.4.2 <= x <= 5.6.3

The supported Typescript version is now 5.4.2 <= x <= 5.6.3. Older versions are no longer supported and newer versions will be added as we validate them.