Recipe Book0.6.0

2.5Guides

Validate recipes

Check recipe input from a CMS, an API, or a form at runtime, and report every issue with its path.

§ 2.54 min readView as Markdown

Validate recipe input that TypeScript can’t check because it arrives at runtime, from a content management system (CMS), a database, an API response or request body, or a form. Pass it to parseRecipe, which accepts unknown, checks every field, and returns a Recipe or every issue it found. In a React app, replace @recipe-book/core with @recipe-book/react/core in this page’s imports. Except for an error thrown by a getter or a proxy in the input, which passes through, parseRecipe doesn’t throw for bad input, so branch on success:

TypeScript
import { parseRecipe } from '@recipe-book/core'

export async function getRecipe(url: string) {
  const response = await fetch(url)
  const result = parseRecipe(await response.json())

  if (!result.success) {
    throw result.error
  }

  return result.data
}

result.error is an Error whose message lists the first 10 issues, so throwing it gives a readable failure. Warnings count toward the 10, so when 10 warnings come first, the issues that failed the parse are only in error.issues. Where you catch it, pass it to isRecipeValidationError before reading its issues: TypeScript then types error.issues with no cast. To keep recipes in a database, store result.data and validate it again when you load it, as Store the recipe shows.

Read issues

parseRecipe doesn’t stop at the first problem, so you see every issue at once:

TypeScript
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  yield: '4',
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cupz' },
    { name: 'egg', quantity: 2, optional: 'no' },
  ],
  steps: ['Whisk the dry ingredients in a large bowl.'],
})

if (!result.success) {
  console.log(result.error.message)
}
result.error.message
"Buttermilk pancakes" has 3 problems:
  ✖ yield                    Add what the recipe makes, e.g. "24 cookies". For a number of servings, use servings: 4.
  ✖ ingredients[0].quantity  Unknown unit "cupz". Did you mean "cups"?
  ✖ ingredients[1].optional  Expected true or false, received "no".
See https://recipe-book.siraj.page/errors/invalid_recipe/

result.error.issues has each issue as data, with a code, a severity, a message, and a path to the value, a list of keys and indexes such as ['ingredients', 0, 'quantity']. Some issues also have a suggestion, so you can offer a “Did you mean” hint: a likely misspelled unit gets the unit it misspells, such as 'cups' for "cupz"; a field name close to a known one gets that one, such as 'steps' for stepz; another format’s name for a field gets that field, such as 'name' for a top-level title; the system 'imperial' gets 'us'; the yield '4 and 6 loaves' gets '4-6 loaves'; and with { parseIngredientLine }, the ingredient line '2 and 1/2 cups flour' gets an invalid_quantity warning suggesting '2 1/2 cups'. Issue codes lists every code with its severity, what it means, and how to fix it.

To see the issues parseRecipe(input, { parseIngredientLine }) gives your own recipe input, paste it into the playground as JSON rather than as a JavaScript object like the ones on this page. Without { parseIngredientLine }, a text ingredient such as '2 cups flour' is an invalid_type error instead.

Validate a form

Form fields give their values as strings. To show each issue next to its form field, match the field to issue.path.join('.'):

TypeScript
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  servings: '4',
  ingredients: [
    { name: 'all-purpose flour', quantity: '' },
    { name: 'egg', quantity: '2', optional: 'on' },
  ],
  steps: ['Whisk the dry ingredients in a large bowl.'],
})

if (!result.success) {
  result.error.issues.map((issue) => [issue.path.join('.'), issue.message]) // [['ingredients.0.quantity', 'Expected a quantity such as "1 ½ cups", received an empty string.'], ['ingredients.1.optional', 'Expected true or false, received "on".']]
}

Servings, yields, and quantities can be strings, as '4' shows, but a time in minutes must be a number, so pass a time field through Number(). Leave out a servings, yield, quantity, or time field the reader left empty, and for optional, pass a checkbox’s checked rather than the 'on' it submits.

Handle warnings

Issues with the severity warning don’t fail the parse. When it succeeds, result.warnings lists them; when it fails, result.error.issues lists them with the issues that failed it. An unknown_field warning means the parse dropped that field, as these misspelled fields show:

TypeScript
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  serving: 4,
  ingredients: [{ name: 'egg', quantiy: 2 }],
  step: ['Whisk the eggs.'],
})

if (!result.success) {
  throw result.error
}

result.warnings.map((issue) => issue.message) // ['Unknown field. Did you mean "quantity"?', 'Recipe has no steps.', 'Unknown field. Did you mean "servings"?', 'Unknown field. Did you mean "steps"?']

The recipe parses, but without its servings, its steps, or the egg’s quantity. To fail a content build on any issue, treat warnings as errors: check result.warnings.length too.

Validate with Standard Schema

recipeSchema wraps parseRecipe in the Standard Schema format, so libraries that accept a Standard Schema can validate recipe input with it. It reads ingredient objects only; for ingredient lines, make a schema with createRecipeSchema({ parseIngredientLine }). In tRPC 11, pass it to .input(), and input is a Recipe:

TypeScript
import { recipeSchema } from '@recipe-book/core'
import { initTRPC } from '@trpc/server'

const t = initTRPC.create()

export const appRouter = t.router({
  saveRecipe: t.procedure
    .input(recipeSchema)
    .mutation(({ input }) => input.id),
})

The library gets only the issues with the severity error, each with a message and a path.

recipeSchema isn’t a Zod or Valibot schema, so it can’t be a field inside z.object() or v.object(). There’s no JSON Schema for recipe input either: check it with parseRecipe or recipeSchema.

Next steps

Contents