npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sanity-typed/faker

v3.0.1

Published

Generate Mock Data from Sanity Schemas

Downloads

374

Readme

@sanity-typed/faker

NPM Downloads GitHub commit activity (branch) GitHub Repo stars GitHub contributors GitHub issues by-label Minified Size License

GitHub Sponsors

Generate Mock Data from Sanity Schemas

Watch How to Offline Your Sanity Client and Generate Mock Data

Page Contents

Install

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

Usage

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

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();
};

sanityDocumentsFaker

While sanityConfigToFaker gives you all the fakers for a given config keyed by type, sometimes you just want an array of all the SanityDocuments. 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 Validity

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.

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

Custom Mocks

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.

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

Breaking Changes

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 it.