Run it as a server
So far the leave App runs for the length of a script. Here it runs as a server: one process that stays up, takes calls over HTTP and runs the queued work without the script asking.
What you build
Section titled “What you build”| You add | What it gives you |
|---|---|
| A loop that runs the queued work | A Listener that runs with no harness.tickAll() |
| An HTTP handler for the App | Mutations and Queries you call with curl |
| A stop on Ctrl-C | A server you start again on the same leave.db |
The App does not change. You write one new file, server.ts.
Before you start
Section titled “Before you start”You need leave.ts and people.ts from chapter 4 of the tutorial. Both stay as they are. Keep your data explains the file leave.db and the Workspace a script creates in it once.
Install three more packages:
npm install express \ @pyn-backend/platform-transport-rest-express \ @tsvcs/tickerStart with a new file, so your lists match the ones here:
rm -f leave.db leave.db-wal leave.db-shm1. Start the server
Section titled “1. Start the server”Create server.ts beside leave.ts and people.ts. Every line that is not marked is in the script from Keep your data. The marked lines are new:
import { randomUUID } from 'node:crypto';
import { createSqliteKnexDatabase } from '@pyn-backend/data-knex-sqlite';import { createHarnessInstance } from '@pyn-backend/platform-harness-public';import { createSqliteInstance } from '@pyn-backend/platform-reactor-sqlite';import { createSqlitePlatformService } from '@pyn-backend/platform-service-sqlite';import { createRestExpress } from '@pyn-backend/platform-transport-rest-express';import { createTestConfigurationService } from '@pyn-backend/service-configuration-test';import { createTestCronService } from '@pyn-backend/service-cron-test';import { createTestSystemService } from '@pyn-backend/service-system-test';import { createTestDynamicConfigService } from '@pyn-backend/test-services-dynamic-config';import { createTestLoggerService } from '@pyn-backend/test-services-logger';import { createLocalTicker } from '@tsvcs/ticker/local';import express from 'express';
import { leaveApp } from './leave';
// A SQLite database in the file leave.db, with the Alpyne tables.const knex = await createSqliteKnexDatabase('leave.db');await knex.current.migrate.latest();
// The services a Runtime depends on.const system = createTestSystemService();const services = { configuration: createTestConfigurationService(), cron: createTestCronService({ system }), dynamicConfig: createTestDynamicConfigService(), knex, logger: createTestLoggerService(), system,};
// The SQLite Runtime with your App loaded.const platform = createSqlitePlatformService(services);const reactor = createSqliteInstance({ ...services, platform }, {});const runtime = { ...services, platform, reactor };const harness = await createHarnessInstance(runtime, leaveApp);
// Create the Workspace on the first run. Every run after that finds it in the file.const workspaceId = '56eef1d9-c851-5e2f-87c7-8759dcf17469';const found = await platform.checkWorkspaceExists(workspaceId);if (!found) await harness.createWorkspace();
// Run the queued work in a loop, with a pause of 100 milliseconds between passes.const ticker = createLocalTicker({ delayMilliseconds: 100 });await ticker.register(reactor);await ticker.register(platform);
// Answer HTTP calls under /api. Each call opens the Workspace as the system.const auth = { tag: 'server', type: 'system', workspaceId } as const;const app = express();app.use(express.json());app.use((request, _response, next) => { Object.assign(request, { traceId: randomUUID() }); next();});app.all('/api/*', async (request, response, next) => { try { const instance = await platform.createInstance(auth); await createRestExpress(instance)(request, response, next); } catch (error) { next(error); }});const port = Number(process.env.PORT ?? 3000);const server = app.listen(port, () => console.log(`Listening on port ${port}`));
// Ctrl-C ends the loop. Then close the port and the database.ticker.onDestroy(async () => { server.close(); await knex.destroy(); return true;});await ticker.start();The new lines do three jobs:
- Run the queued work.
createLocalTickermakes a loop. The script gives it the two parts thatharness.tickAll()ran,reactorandplatform.ticker.start()runs both, pauses 100 milliseconds and runs them again, until you stop the process. - Answer HTTP calls.
createRestExpressruns a call as a Mutation or a Query of your App. The path names it:/api/leave/mutation/requestis therequestMutation of the Appleave.createRestExpressskips the first part of the path, and this script fixes it toapi. - Stop on Ctrl-C. Ctrl-C ends the loop. Then the script closes the port and the database.
Two steps prepare each call. express.json() reads the JSON the call sends. Then the script gives the call a trace id, which createRestExpress reads when it runs a Mutation.
Every call runs as the system, so it passes every access rule you wrote in chapter 2 of the tutorial. Anyone who can reach the port can make any call.
Start the server:
PYN_ENV=local npx tsx server.tsYou should see:
Listening on port 3000The process keeps running. It listens on port 3000, or on the port you name in PORT.
2. Call it
Section titled “2. Call it”Leave the server running and open a second terminal. Request five days of leave:
curl -X POST localhost:3000/api/leave/mutation/request \ -H 'content-type: application/json' \ -d '{"days":5,"reason":"Summer holiday"}'The request Mutation returns the new request as JSON. curl prints it on one line. Here it is on several lines:
{ "createdAt": "2020-01-01T00:00:00.000Z", "id": "e57a0123-905a-4ada-998a-e4880c1593a5", "isArchived": false, "parentId": "56eef1d9-c851-5e2f-87c7-8759dcf17469", "properties": { "reason": "Summer holiday", "days": 5 }, "relations": {}, "rolePrns": [ "prn::leave:template/leaveRequest/role/staff" ], "state": "pending", "templatePrn": "prn::leave:template/leaveRequest"}Your id differs. createdAt reads 1 January 2020 because the server runs on the clock from the tutorial, which moves only when a script moves it.
The other responses on this page are trimmed to three of these fields: id, properties and state.
List the requests:
curl localhost:3000/api/leave/query/list[ { "id": "e57a0123-905a-4ada-998a-e4880c1593a5", "properties": { "reason": "Summer holiday", "days": 5 }, "state": "pending" }]Approve the request. Put the id from your own response in place of this one:
curl -X POST localhost:3000/api/leave/mutation/approve \ -H 'content-type: application/json' \ -d '{"id":"e57a0123-905a-4ada-998a-e4880c1593a5"}'{ "id": "e57a0123-905a-4ada-998a-e4880c1593a5", "properties": { "reason": "Summer holiday", "days": 5 }, "state": "approved"}3. Watch the Listener run
Section titled “3. Watch the Listener run”Look at the server’s terminal:
Listening on port 3000Listener: "Summer holiday" is approvedThe second line is the Listener in leave.ts. approve saved the Event and returned, and nothing in server.ts calls harness.tickAll(). The loop found the Event on its next pass and ran the Listener.
4. Stop it, then start it again
Section titled “4. Stop it, then start it again”In the server’s terminal, press Ctrl-C. The process ends, and leave.db holds the request.
Start the server again:
PYN_ENV=local npx tsx server.tsIt prints its one line. No Listener: line follows, because that work is done. From the second terminal, list the requests:
curl localhost:3000/api/leave/query/list[ { "id": "e57a0123-905a-4ada-998a-e4880c1593a5", "properties": { "reason": "Summer holiday", "days": 5 }, "state": "approved" }]The request is still there, approved. The new process found the Workspace in leave.db and opened it.
What you have now
Section titled “What you have now”- A process that stays up.
server.tsruns until you press Ctrl-C. - Your App over HTTP. A Mutation answers at
/api/leave/mutation/<name>, a Query at/api/leave/query/<name>. - Work that runs without being asked. The loop runs a Listener a moment after the call that saved its Event.
- The same data after a restart. Stop the server, start it again, and every request is still in
leave.db.

