Skip to content

Latest commit

 

History

History
61 lines (39 loc) · 2.03 KB

File metadata and controls

61 lines (39 loc) · 2.03 KB

Jsonlet Examples

README · API Reference · Contributing

This directory contains real-world examples demonstrating how to use Jsonlet in production-like scenarios.

Example: Local CLI Task Manager (todo.ts)

A fully typed, validating command-line Todo application. It demonstrates how to seamlessly combine Jsonlet's atomic persistence with Zod for strict schema validation.

Features Demonstrated

  • Type-safe State: Infers TypeScript types directly from the Zod schema.
  • On-Load Validation: Rejects malformed or manually edited JSON files before they can crash your app.
  • Transactional Updates: Uses db.update() to mutate state safely.
  • Synchronous Reads: Uses db.read() to fetch the deeply frozen, cached state.
  • Cross-process Safety: Try running multiple add commands simultaneously from different terminals—Jsonlet's file locks guarantee no data is lost!

How to Run

From the repository root, install the development dependencies:

bun install

Then use Bun to execute the CLI commands.

1. Add a task

bun run examples/todo.ts add "Write documentation"
bun run examples/todo.ts add "Publish to npm"

2. List tasks

bun run examples/todo.ts list

Take note of the short ID printed next to each task.

3. Complete a task

bun run examples/todo.ts complete <short-id>

Behind the Scenes

When you run this example, Jsonlet automatically creates a data/ directory in the root of your project and generates todo.json.

Try a Validation Failure

  1. Open data/todo.json in your text editor.
  2. Manually change a "completed": false boolean to a string: "completed": "not yet".
  3. Run bun run examples/todo.ts list.
  4. Watch Jsonlet and Zod instantly intercept the corrupted state and throw a safe validation error, protecting your application from continuing with bad data!

The generated data/todo.json file is local example state and should not be committed.