Using Checked Data
Part of the REST APIs section of Coddy's Node.js journey. Lesson 8 of 25.
A schema can return either checked data or information about a problem. safeParse returns an object whose success field tells you which happened. On success, data holds the checked value.
const result = Book.safeParse(body);
if (result.success) {
return result.data;
}
return {error: 'Invalid book'};Rules can transform values as well as reject them. z.string().trim() removes surrounding spaces. Save the checked data to keep that change. Saving the original body would put the unwanted spaces back. The supplied schema already has its rules.
trim() removes surrounding spaces. The following min(1) requires at least one character, so a title containing only spaces fails.
Challenge
EasyThis is a small practice project. Its setup is provided; edit only exercise.js.
Use the supplied Task schema. Return {"ok":true,"title":...} with the trimmed title on success, or {"ok":false} on failure. POST {"title":" Read "} to /result gives {"ok":true,"title":"Read"}. A title of 42 gives {"ok":false}.
Also try {"title":" "}: it must return {"ok":false}.
The initial GET /result uses the supplied example {"title": " Read "}. 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().trim().min(1) });
export function exercise(body) {
return { ok: true, title: body.title };
}
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST4Browsers, Versions and Config
What Is an OriginAllowing Another OriginCORSA Page That Calls the API2Validation and Errors
Validating InputPractice on your own: Express playground