Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/shop/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
.lo1/
72 changes: 72 additions & 0 deletions examples/shop/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Shop example

A small system for trying lo1: a web frontend, an API and Postgres, with a database migration and seed data that run before the API starts.

```
postgres (infra.compose.yaml)
└─ migrate (init task) ─ seed (init task) ─ api ─ web
```

You need Node.js 24+ and Docker. Run `lo1 doctor` to check.

## Run it

```bash
npx degit newstack-cloud/lo1/examples/shop shop
cd shop
lo1 up
```

`lo1 up` asks for `sudo` once, to add `api.shop.local` and `web.shop.local` to your hosts file and trust lo1's local certificate authority. It then starts Postgres, runs `migrate` and `seed`, starts the API, waits for its health check, and starts the web app:

```
Workspace shop is ready in 4.1s
infrastructure 2.4s · services 1.7s

Services:
api https://api.shop.local
web https://web.shop.local
```

Open https://web.shop.local to see the products, read from Postgres through the API.

## Things to try

| Command | What it does |
| ------------------------ | --------------------------------------------------------------- |
| `lo1 status` | Shows each service's health. Exits 0 when everything is up. |
| `lo1 logs api` | Tails the API's log. |
| `lo1 restart seed` | Runs the seed again, putting the products back how they started. |
| `lo1 restart api` | Restarts the API and waits for its health check. |
| `lo1 up --detach` | Starts everything in the background and returns once it's ready. |
| `lo1 down` | Stops everything. Add `--clean` to delete the database volume. |

## How it fits together

- [`lo1.yaml`](./lo1.yaml) lists the services. `migrate` and `seed` are init tasks: they run once, in order, and must exit 0 before anything that depends on them starts.
- [`infra.compose.yaml`](./infra.compose.yaml) is an ordinary Docker Compose file for Postgres. lo1 waits for its health check before running the migration.
- The web app finds the API through `LO1_SERVICE_API_PROXY_URL`, which lo1 sets for every service, and the API only accepts browser requests from the web app's URL, `LO1_SERVICE_WEB_PROXY_URL`. See [`web/src/config.js`](./web/src/config.js) and [`api/src/config.js`](./api/src/config.js).

## How the code is organised

The services are small, but they're laid out the way a real one would be. Each module has one job, and each depends only on what it's given.

| File | Its one job |
| --- | --- |
| [`api/src/config.js`](./api/src/config.js) | Reads the environment, once. Nothing else touches `process.env`. |
| [`api/src/server.js`](./api/src/server.js) | The composition root: creates the pool and starts the server. |
| [`api/src/app.js`](./api/src/app.js) | Wires repositories and routes together into a request handler. |
| [`api/src/http/router.js`](./api/src/http/router.js) | Dispatches requests to routes. A new endpoint is a new route; the router doesn't change. |
| [`api/src/products/`](./api/src/products/) | The product routes, and the repository that holds all the product SQL. |
| [`api/src/migrations/`](./api/src/migrations/) | Numbered migrations, recorded in `schema_migrations` so each runs once. To change the schema, add a file. |
| [`web/src/handler.js`](./web/src/handler.js) | Serves the page's files and `/config.json`, with a content security policy. |
| [`web/public/app.js`](./web/public/app.js) | Fetches the products and renders them with `textContent`, never `innerHTML`. |

## Run the tests

```bash
cd api && npm install && npm test # starts a throwaway Postgres in Docker first
cd web && npm test
```

The API's tests run against real Postgres, from [`api/test/compose.yaml`](./api/test/compose.yaml), on port 54330, so they can run alongside `lo1 up`. Each test file works in its own schema. Stop the test database with `npm run test:db:down`.
162 changes: 162 additions & 0 deletions examples/shop/api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions examples/shop/api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "shop-api",
"private": true,
"type": "module",
"engines": {
"node": ">=24"
},
"scripts": {
"start": "node src/server.js",
"migrate": "node src/migrate.js",
"seed": "node src/seed.js",
"test": "npm run test:db:up --silent && node --test \"test/**/*.test.js\"",
"test:db:up": "docker compose -f test/compose.yaml up -d --wait --quiet-pull",
"test:db:down": "docker compose -f test/compose.yaml down -v"
},
"dependencies": {
"pg": "8.23.1"
}
}
21 changes: 21 additions & 0 deletions examples/shop/api/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { createRouter } from "./http/router.js";
import { healthRoutes } from "./health/routes.js";
import { createProductRepository } from "./products/repository.js";
import { productRoutes } from "./products/routes.js";

/**
* Wires the API together: repositories on top of the pool, routes on top of
* the repositories. Returns a Node request handler. The pool and settings
* come from the caller, so tests can run the real API on a test database.
*/
export function createApp({ pool, allowedOrigin, onError }) {
const products = createProductRepository(pool);

return createRouter(
[...healthRoutes(() => pool.query("SELECT 1")), ...productRoutes(products)],
{
headers: { "access-control-allow-origin": allowedOrigin, vary: "Origin" },
onError,
},
);
}
19 changes: 19 additions & 0 deletions examples/shop/api/src/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Reads the API's settings from the environment, once. The rest of the code
* is given these values and never reads `process.env` itself.
*/
export function loadConfig(env = process.env) {
return {
port: Number(env.PORT ?? 4100),
databaseUrl: required(env, "DATABASE_URL"),
// lo1 gives every service each other service's URLs. The web app's public
// URL is the only origin allowed to call this API from a browser.
allowedOrigin: env.LO1_SERVICE_WEB_PROXY_URL ?? "http://localhost:4200",
};
}

function required(env, name) {
const value = env[name];
if (!value) throw new Error(`${name} is not set`);
return value;
}
6 changes: 6 additions & 0 deletions examples/shop/api/src/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import pg from "pg";

/** A connection pool for Postgres. Everything else takes the pool as a parameter. */
export function createPool(databaseUrl) {
return new pg.Pool({ connectionString: databaseUrl, max: 5 });
}
17 changes: 17 additions & 0 deletions examples/shop/api/src/health/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* `GET /health`, which lo1's readiness probe calls. It only reports healthy
* when the database answers, so lo1 waits for a working API, not just a
* listening one.
*/
export function healthRoutes(checkDatabase) {
return [
{
method: "GET",
path: "/health",
handle: async () => {
await checkDatabase();
return { body: { ok: true } };
},
},
];
}
34 changes: 34 additions & 0 deletions examples/shop/api/src/http/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Builds a Node request handler from a list of routes.
*
* A route is `{ method, path, handle }`. `handle(req)` returns
* `{ status?, body }` and never touches the response, so a route can be
* tested without a server. Adding an endpoint means adding a route; the
* router itself doesn't change.
*/
export function createRouter(routes, { headers = {}, onError = console.error } = {}) {
const byKey = new Map(routes.map((route) => [routeKey(route.method, route.path), route]));

return async (req, res) => {
const { pathname } = new URL(req.url, "http://localhost");
const route = byKey.get(routeKey(req.method, pathname));
if (!route) return sendJson(res, 404, { error: "not found" }, headers);

try {
const { status = 200, body } = await route.handle(req);
sendJson(res, status, body, headers);
} catch (err) {
onError(err);
sendJson(res, 500, { error: "internal error" }, headers);
}
};
}

function routeKey(method, path) {
return `${method} ${path}`;
}

function sendJson(res, status, body, headers) {
res.writeHead(status, { ...headers, "content-type": "application/json; charset=utf-8" });
res.end(JSON.stringify(body));
}
13 changes: 13 additions & 0 deletions examples/shop/api/src/migrate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { loadConfig } from "./config.js";
import { createPool } from "./db.js";
import { migrations } from "./migrations/index.js";
import { runMigrations } from "./migrations/run.js";

// Run by lo1 as the `migrate` init task, before `seed` and the API start.
const pool = createPool(loadConfig().databaseUrl);
try {
await runMigrations(pool, migrations);
console.log("migrations applied");
} finally {
await pool.end();
}
11 changes: 11 additions & 0 deletions examples/shop/api/src/migrations/001-create-products.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const name = "001-create-products";

export async function up(db) {
await db.query(`
CREATE TABLE IF NOT EXISTS products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
price_pence INTEGER NOT NULL CHECK (price_pence >= 0)
)
`);
}
4 changes: 4 additions & 0 deletions examples/shop/api/src/migrations/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import * as createProducts from "./001-create-products.js";

/** Every migration, in the order they run. To change the schema, add a file and list it here. */
export const migrations = [createProducts];
Loading
Loading