# Complete example

**Supply requests**: everyone who can open the app asks for supplies and sees their own requests. Managers see all requests and answer them.

It has no dependencies and no build step. An assistant without a terminal can send these files with [`deploy_app`](https://boring-cloud.app/docs/build-from-chat.md). The tests of the platform run this exact code.

What to notice: the backend decides who sees and changes what, every SQL value is bound, every input is checked, and text is shown with `textContent`.

## Manifest

```json
{
  "schemaVersion": 1,
  "name": "Supply requests",
  "description": "Ask for office supplies and follow the answer",
  "runtime": "worker-js",
  "entry": "dist/worker.mjs",
  "assets": "dist/client",
  "database": true
}
```

## worker.mjs

```js
const json = (data, status = 200) => Response.json(data, { status });
const STATUSES = ["open", "approved", "refused"];

let ready;
const ensureSchema = (db) =>
  (ready ??= db
    .batch([
      db.prepare(`CREATE TABLE IF NOT EXISTS requests (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        item TEXT NOT NULL,
        quantity INTEGER NOT NULL,
        status TEXT NOT NULL DEFAULT 'open',
        created_by TEXT NOT NULL,
        created_by_name TEXT NOT NULL,
        created_at TEXT NOT NULL
      )`),
      db.prepare("CREATE INDEX IF NOT EXISTS requests_by_author ON requests (created_by, id)"),
    ])
    .catch((e) => {
      ready = undefined;
      throw e;
    }));

const readBody = async (request) => {
  try {
    return (await request.json()) ?? {};
  } catch {
    return {};
  }
};

const handle = async (request, db, url, user) => {
  const isManager = user.role === "manager";

  if (url.pathname === "/api/requests" && request.method === "GET") {
    const { results } = await db
      .prepare(
        `SELECT id, item, quantity, status, created_by_name AS author, created_at AS createdAt
         FROM requests WHERE ?1 = 1 OR created_by = ?2 ORDER BY id DESC LIMIT 200`,
      )
      .bind(isManager ? 1 : 0, user.id)
      .all();
    return json({ requests: results, isManager });
  }

  if (url.pathname === "/api/requests" && request.method === "POST") {
    const input = await readBody(request);
    const item = typeof input.item === "string" ? input.item.trim() : "";
    const { quantity } = input;
    if (!item || item.length > 120) return json({ error: "Name the item, in at most 120 characters." }, 400);
    if (!Number.isInteger(quantity) || quantity < 1 || quantity > 999)
      return json({ error: "The quantity must be between 1 and 999." }, 400);
    await db
      .prepare(
        "INSERT INTO requests (item, quantity, created_by, created_by_name, created_at) VALUES (?, ?, ?, ?, ?)",
      )
      .bind(item, quantity, user.id, user.name, new Date().toISOString())
      .run();
    return json({ ok: true }, 201);
  }

  const match = url.pathname.match(/^\/api\/requests\/(\d{1,12})$/);
  if (match && request.method === "PATCH") {
    if (!isManager) return json({ error: "Only managers can answer a request." }, 403);
    const { status } = await readBody(request);
    if (!STATUSES.includes(status)) return json({ error: "Unknown answer." }, 400);
    const { meta } = await db
      .prepare("UPDATE requests SET status = ? WHERE id = ?")
      .bind(status, Number(match[1]))
      .run();
    return meta.changes ? json({ ok: true }) : json({ error: "This request no longer exists." }, 404);
  }

  return json({ error: "Not found." }, 404);
};

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (url.pathname === "/__boringcloud/health") return json({ ok: true });
    const user = {
      id: request.headers.get("x-boringcloud-user-id"),
      name: decodeURIComponent(request.headers.get("x-boringcloud-user-name") ?? ""),
      role: request.headers.get("x-boringcloud-role"),
    };
    if (!user.id) return json({ error: "Sign in first." }, 401);
    try {
      await ensureSchema(env.APP_DB);
      return await handle(request, env.APP_DB, url, user);
    } catch (e) {
      console.error(e instanceof Error ? e.message : e);
      return json({ error: "Something went wrong. Try again." }, 500);
    }
  },
};
```

## index.html

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Supply requests</title>
    <link rel="stylesheet" href="/_boringcloud/brand.css" />
    <link rel="stylesheet" href="/style.css" />
    <script type="module" src="/app.js"></script>
  </head>
  <body>
    <main>
      <h1>Supply requests</h1>
      <form id="new">
        <label>Item <input name="item" required maxlength="120" autocomplete="off" /></label>
        <label>Quantity <input name="quantity" type="number" min="1" max="999" value="1" required /></label>
        <button>Ask</button>
      </form>
      <p id="message" role="status">Loading…</p>
      <ul id="list"></ul>
    </main>
  </body>
</html>
```

## app.js

```js
const form = document.querySelector("#new");
const message = document.querySelector("#message");
const list = document.querySelector("#list");
const LABELS = { open: "Waiting", approved: "Approved", refused: "Refused" };

const api = async (path, method = "GET", body) => {
  const res = await fetch(`/api${path}`, {
    method,
    headers: body ? { "content-type": "application/json" } : {},
    body: body ? JSON.stringify(body) : undefined,
  });
  if (res.status === 401) {
    location.reload();
    return new Promise(() => {});
  }
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error ?? "Something went wrong. Try again.");
  return data;
};

const el = (tag, text, className) => {
  const node = document.createElement(tag);
  if (text) node.textContent = text;
  if (className) node.className = className;
  return node;
};

const load = async () => render(await api("/requests"));

const run = async (button, action) => {
  button.disabled = true;
  try {
    await action();
    await load();
    return true;
  } catch (e) {
    message.textContent = e.message;
    return false;
  } finally {
    button.disabled = false;
  }
};

const answerButton = (request, status, label) => {
  const button = el("button", label, "plain");
  button.type = "button";
  button.setAttribute("aria-label", `${label}: ${request.item}`);
  button.addEventListener("click", () =>
    run(button, () => api(`/requests/${request.id}`, "PATCH", { status })),
  );
  return button;
};

const render = ({ requests, isManager }) => {
  message.textContent = requests.length ? "" : "No requests yet.";
  list.replaceChildren(
    ...requests.map((request) => {
      const row = el("li");
      const text = el("div");
      text.append(
        el("strong", `${request.quantity} × ${request.item}`),
        el("span", `${request.author}, ${new Date(request.createdAt).toLocaleDateString()}`),
      );
      row.append(text, el("em", LABELS[request.status], request.status));
      if (isManager && request.status === "open")
        row.append(answerButton(request, "approved", "Approve"), answerButton(request, "refused", "Refuse"));
      return row;
    }),
  );
};

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const { item, quantity } = Object.fromEntries(new FormData(form));
  const done = await run(form.querySelector("button"), () =>
    api("/requests", "POST", { item, quantity: Number(quantity) }),
  );
  if (done) form.reset();
});

load().catch((e) => {
  message.textContent = e.message;
});
```

## style.css

```css
:root {
  --accent: var(--brand-primary, #1f4fd8);
}
* {
  box-sizing: border-box;
}
body {
  margin: 0;
  color: #1c1c1f;
  font:
    16px / 1.5 system-ui,
    sans-serif;
  font-family: var(--brand-font-body, system-ui, sans-serif);
}
main {
  max-width: 44rem;
  margin: 0 auto;
  padding: 2rem 1rem;
}
h1 {
  font-family: var(--brand-font-heading, inherit);
}
form {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  align-items: end;
}
label {
  display: grid;
  gap: 0.25rem;
  font-size: 0.875rem;
}
label:first-child {
  flex: 1 1 14rem;
}
input,
button {
  min-height: 2.5rem;
  padding: 0 0.75rem;
  border: 1px solid #85858c;
  border-radius: 8px;
  font: inherit;
}
button {
  border-color: var(--accent);
  background: var(--accent);
  color: #ffffff;
  cursor: pointer;
}
button.plain {
  border-color: #85858c;
  background: #ffffff;
  color: #1c1c1f;
}
button:disabled {
  opacity: 0.6;
}
:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}
ul {
  padding: 0;
  list-style: none;
}
li {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  align-items: center;
  padding: 0.75rem 0;
  border-top: 1px solid #dcdce0;
}
li div {
  display: grid;
  flex: 1 1 12rem;
  overflow-wrap: anywhere;
}
li span {
  color: #5c5c63;
  font-size: 0.875rem;
}
em {
  font-style: normal;
}
em.approved {
  color: #166534;
}
em.refused {
  color: #b42318;
}
```

## Larger examples

With a terminal, `boringcloud init` copies a project to start from:

| Template       | Shows                                                                     |
| -------------- | ------------------------------------------------------------------------- |
| `team-tracker` | React, TypeScript, Vite, a database with an added column                  |
| `web-research` | plain frontend, TypeScript backend, an external API, files and a database |
| `hello-world`  | the smallest project with a backend                                       |
