Schema
Validates JSON data received over HTTP using typed schemas. This is a typical use case: data arrives from an external API as unknown, and you need to verify its shape before using it. See the schema API reference for caveats, when to use, and the full type surface.
Hardware
- Any ESP32 board with WiFi
- USB cable
Code
import * as s from 'mikro/schema'
// Define a schema for the API response
const WeatherResponse = s.object({
temperature: s.number(),
humidity: s.number(),
description: s.optional(s.string()),
})
// Simulate data arriving from an HTTP API
const raw: unknown = JSON.parse('{"temperature": 22.5, "humidity": 45.2}')
const result = s.parse(WeatherResponse, raw)
if (result.ok) {
console.log(`Temperature: ${result.value.temperature}`)
console.log(`Humidity: ${result.value.humidity}`)
} else {
console.error('Invalid response:', result.error)
}Walkthrough
Define a schema.
s.object({...})describes the expected shape. Each field gets a type validator likes.number()ors.string().Parse untrusted data.
s.parse()checks the data against the schema and returns aResult. On success,result.valueis fully typed. On failure,result.errortells you what went wrong and where.No exceptions. Validation never throws. You always get a
Resultto handle both cases explicitly.
Create project
pnpm create mikro --template schemanpm create mikro -- --template schemayarn create mikro --template schemabun create mikro --template schemaRun it
pnpm install
pnpm mikro flash # only needed once per board
pnpm mikro devnpm install
npx mikro flash # only needed once per board
npx mikro devyarn install
yarn mikro flash # only needed once per board
yarn mikro devbun install
bunx mikro flash # only needed once per board
bunx mikro devThe console prints the valid readings and commands, and clear error messages for the invalid ones.