Menu
CoddyTech

Optional Fields

Part of the REST APIs section of Coddy's Node.js journey. Lesson 9 of 25.

A complete task needs a title and a done value. A PATCH request may change only one of them. Calling .partial() on an object schema makes its fields optional while keeping the rules for any fields that are present.

const ChangeBook = Book.partial();
ChangeBook.safeParse({year: 2000});

The omitted title is allowed, but a supplied year must still be a number. Partial does not turn incorrect values into valid ones. The original schema remains unchanged, so a route that replaces a complete resource can continue to require every field.

Book.partial({ pages: true }) makes only pages optional; other fields stay required. A creation request often omits a field with a default while still requiring the main title. After parsing, const { pages = 1 } = result.data supplies 1 when the field was omitted.

challenge icon

Challenge

Easy

Edit the two schema assignments in exercise.js. Keep Task as the complete record. Make ChangeTask accept omitted fields for PATCH. Make NewTask require a title but allow done to be omitted.

POST {} to /result: expect {"change":true,"create":false}. A body of {"title":"Read"} passes both. Supplied values still need the right type: {"done":"false"} fails both.

The initial GET /result uses the supplied example {}. Use POST /result with a JSON body to try other inputs.

Try it yourself

import { z } from 'zod';
const Task = z.object({ title: z.string(), done: z.boolean() });
const ChangeTask = Task;
const NewTask = Task;
export function exercise(body) {
    return { change: ChangeTask.safeParse(body).success, create: NewTask.safeParse(body).success };
}

All lessons in REST APIs

Practice on your own: Express playground