Browse recipes

Validate data and read a nested path

Normalize one profile input before rendering its accepted values.

Table of contents

APIs used

mount
Starts a Valyrian.js application on a DOM target.
ensureIn
Checks whether a value belongs to an allowed collection.
get
Reads a nested value by path and returns the provided fallback when needed.
isFiniteNumber
Checks for a finite numeric value.
pick
Creates an object with the selected keys from a source value.
set
Updates a nested object path.

Run this recipe

Starting project
Use the local TSX and ESM project from Stage 1 with Valyrian.js installed and its ESM browser build configured.
File
Replace src/client-entry.tsx with this recipe snippet.
Run
Run npm run build, serve public with npx --yes serve@14.2.5 public --listen 8000, open http://localhost:8000 and use the example's visible controls.
Observable result
Valid input renders Arya: editor. Unsupported roles and non-finite page sizes raise explicit type errors.

Starting point

Select allowed fields, validate their values and read one nested profile value.

Steps

Use pick to select role and pageSize, ensureIn to check the allowed role, get to read profile.name with a fallback and set when a nested value must change.

ts
import { mount } from "valyrian.js";
import { ensureIn, get, isFiniteNumber, pick, set } from "valyrian.js/utils";

type Input = {
  role: string;
  pageSize: number;
  profile: { name: string };
  ignored: boolean;
};

const input: Input = {
  role: "editor",
  pageSize: 20,
  profile: { name: "Arya" },
  ignored: true,
};
const safe = pick<Input, "role" | "pageSize">(input, ["role", "pageSize"]);
const role: string = safe.role;
set(input, "profile.name", "Arya");

if (!ensureIn(role, ["viewer", "editor"])) {
  throw new TypeError("Unsupported role");
}
if (!isFiniteNumber(safe.pageSize)) {
  throw new TypeError("Page size must be finite");
}

const name = get(input, "profile.name", "Anonymous");
mount("body", () => `${name}: ${role}`);

Result

Valid input renders Arya: editor. Unsupported roles and non-finite page sizes raise explicit type errors.

Continue