Skip to content

Programmatic API

The programmatic API lets you start and stop a yRest server from inside your test suite or any Node.js script — no CLI, no separate process. Import createYrestServer, pass a config object, and use the running server URL in your tests.

import { createYrestServer } from "@yrest/cli";
const server = createYrestServer({ file: "./tests/db.yml", port: 3070 });
await server.start();
// run tests against http://localhost:3070
await server.stop();
OptionTypeDefaultDescription
filestring—Path to the YAML database file
portnumber3070Port to listen on
hoststring"localhost"Host to bind
basestring""URL prefix for all routes
readonlybooleanfalseReject all write operations
delaynumber0Simulated latency in ms
snapshotbooleanfalseEnable snapshot/reset endpoints

server.collection<T>(name) returns a typed CRUD handle over the running data. Use it to seed or inspect state in a test without going through HTTP:

import { createYrestServer } from "@yrest/cli";
import type { User } from "./db.types"; // from `yrest types db.yml -o db.types.ts`
const server = createYrestServer({ file: "./tests/db.yml", port: 0 });
await server.start();
const users = server.collection<User>("users");
users.create({ name: "Ana", email: "ana@test.com" }); // id assigned by the server
const res = await fetch(`${server.url}/users`);
expect(await res.json()).toHaveLength(users.count());
MethodReturnsDescription
findAll()T[]Every item, in stored order
findById(id)T | undefinedItem by id — 1 and "1" both match
findWhere(fn)T[]Items for which the predicate returns true
count()numberNumber of items
create(data)TAdds an item; the id is generated when omitted
update(id, patch)T | undefinedMerges patch into the item (the id cannot change)
delete(id)T | undefinedRemoves the item and returns it
  • Changes are visible to HTTP clients immediately and are persisted to db.yml exactly like REST writes. With inline data they stay in memory.
  • create() uses the server’s id strategy (increment by default).
  • Returned items are copies: changing one does not change the stored data — use update().
  • collection() throws for a collection that does not exist, and when called before start().

The same handle is available inside handler functions as ctx.collection. Generate User and the other item types with yrest types.