2.3.4 • Published 2 months ago

@sanity-typed/zod v2.3.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

@sanity-typed/zod

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

GitHub Sponsors

Watch How to Generate Zod Schemas for Sanity Documents

Generate Zod Schemas from Sanity Schemas

Page Contents

Install

npm install sanity zod @sanity-typed/zod

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 { 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!
 *  }
 */

client-with-zod.ts:

import config from "sanity.config";
import type { SanityValues } from "sanity.config";

import { createClient } from "@sanity-typed/client";
import { sanityConfigToZods } from "@sanity-typed/zod";

export const client = createClient<SanityValues>({
  projectId: "59t1ed5o",
  dataset: "production",
  useCdn: true,
  apiVersion: "2023-05-23",
});

/** Zod Parsers for all your types! */
const sanityZods = sanityConfigToZods(config);
/**
 * typeof sanityZods === {
 *   [type in keyof SanityValues]: ZodType<SanityValues[type]>;
 * }
 */

export const makeTypedQuery = async () => {
  const results = await client.fetch('*[_type=="product"]');

  return results.map((result) => sanityZods.product.parse(result));
};
/**
 *  typeof makeTypedQuery === () => Promise<{
 *    _createdAt: string;
 *    _id: string;
 *    _rev: string;
 *    _type: "product";
 *    _updatedAt: string;
 *    productName?: string;
 *    tags?: {
 *      _key: string;
 *      label?: string;
 *      value?: string;
 *    }[];
 *  }[]>
 */

sanityDocumentsZod

While sanityConfigToZods gives you all the types for a given config keyed by type, sometimes you just want a zod union of all the SanityDocuments. Drop it into sanityDocumentsZod:

import type { sanityConfigToZods, sanityDocumentsZod } from "@sanity-typed/zod";

const config = defineConfig({
  /* ... */
});

const zods = sanityConfigToZods(config);
/**
 *  zods === { [type: string]: typeZodParserButSomeTypesArentDocuments }
 */

const documentsZod = sanityDocumentsZod(config, zods);
/**
 *  documentsZod === z.union([Each, Document, In, A, Union])
 */

Validations

All validations except for custom are included in the zod parsers. However, if there are custom validators you want to include, using enableZod on the validations includes it:

import { defineConfig, defineField, defineType } from "@sanity-typed/types";
import { enableZod, sanityConfigToZods } from "@sanity-typed/zod";

export const product = defineType({
  name: "product",
  type: "document",
  title: "Product",
  fields: [
    defineField({
      name: "productName",
      type: "string",
      title: "Product name",
      validation: (Rule) =>
        Rule.custom(
          () => "fail for no reason, but only in sanity studio"
        ).custom(
          enableZod((value) => "fail for no reason, but also in zod parser")
        ),
    }),
    // ...
  ],
});

// Everything else the same as before...
const config = defineConfig({
  projectId: "your-project-id",
  dataset: "your-dataset-name",
  schema: {
    types: [
      product,
      // ...
    ],
  },
});

const zods = sanityConfigToZods(config);

expect(() =>
  zods.product.parse({
    productName: "foo",
    /* ... */
  })
).toThrow("fail for no reason, but also in zod parser");

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.

Types match config but not actual documents

As your sanity driven application grows over time, your config is likely to change. Keep in mind that you can only derive types of your current config, while documents in your Sanity Content Lake will have shapes from older configs. This can be a problem when adding new fields or changing the type of old fields, as the types won't can clash with the old documents.

Ultimately, there's nothing that can automatically solve this; we can't derive types from a no longer existing config. This is a consideration with or without types: your application needs to handle all existing documents. Be sure to make changes in a backwards compatible manner (ie, make new fields optional, don't change the type of old fields, etc).

Another solution would be to keep old configs around, just to derive their types:

const config = defineConfig({
  schema: {
    types: [foo],
  },
  plugins: [myPlugin()],
});

const oldConfig = defineConfig({
  schema: {
    types: [oldFoo],
  },
  plugins: [myPlugin()],
});

type SanityValues =
  | InferSchemaValues<typeof config>
  | InferSchemaValues<typeof oldConfig>;

This can get unwieldy although, if you're diligent about data migrations of your old documents to your new types, you may be able to deprecate old configs and remove them from your codebase.

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

2.3.4

2 months ago

2.3.3

3 months ago

2.3.2

3 months ago

2.3.1

3 months ago

2.3.0

4 months ago

2.2.1

4 months ago

2.2.0

4 months ago

2.1.3

5 months ago

2.1.2

5 months ago

2.1.1

5 months ago

2.1.0

5 months ago

2.0.1

5 months ago

2.0.0

5 months ago

1.11.16

5 months ago

1.11.15

5 months ago

1.11.14

5 months ago

1.11.13

5 months ago

1.11.12

5 months ago

1.11.11

5 months ago

1.11.10

5 months ago

1.11.9

5 months ago

1.11.8

5 months ago

1.11.7

5 months ago

1.11.6

5 months ago

1.11.5

6 months ago

1.11.4

6 months ago

1.11.3

6 months ago

1.11.2

7 months ago

1.11.1

7 months ago

1.11.0

7 months ago

1.10.1

7 months ago

1.10.0

7 months ago

1.9.1

7 months ago

1.9.0

7 months ago

1.8.8

7 months ago

1.8.7

7 months ago

1.8.6

7 months ago

1.8.5

7 months ago

1.8.4

7 months ago

1.8.3

7 months ago

1.8.2

7 months ago

1.8.1

7 months ago

1.8.0

7 months ago

1.7.1

7 months ago

1.7.0

7 months ago

1.6.0

7 months ago

1.5.2

8 months ago

1.5.1

8 months ago

1.5.0

8 months ago

1.4.2

8 months ago

1.4.1

8 months ago

1.4.0

8 months ago

1.3.0

8 months ago

1.2.0

8 months ago

1.1.0

8 months ago

1.0.5

8 months ago

1.0.4

8 months ago

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago