functions-database example #

View this page as Markdown

On this page

Deploy a serverless example with a notes page, a function and a PostgreSQL database.

No sign-in is required. Anyone with the address can read every note and add notes.

For the same notes service as a server application, see server-database.

These files come from the same source as the scaffold command. They are the starter files before the command installs dependencies.

Read the complete starter source under File contents, or open a text download under Files. With read_documentation, use the file path from the Files table as section, for example functions/api/notes.js. To continue the page, use next_offset with the same stamp.

With a shell #

This template needs no Turn Zero sign-in or token and downloads no library package. Run this in a new project's root:

turnzero scaffold --origin https://dev.turnzero.ai --template functions-database

Follow the command's next steps. It writes the application in app/, installs dependencies, and runs the tests. The turnzero command explains setup and options.

From a chat #

A Cloud tool name without a prefix is its HTTP API name; your MCP connection lists it with tzcloud_ before it. Account tools such as read_rate_card keep their shorter names. The copied AGENTS.md instructions below use the names listed by the MCP connection.

For this example as it stands, follow the calls and checks below. To adapt it, read Deploying from a chat.

The scaffold can bind its manifest to an application with --application <application id>. From a chat, name the application explicitly in submit_manifest and deploy_files. The platform uses the application named in the call and checks an uploaded manifest's optional application ID only for lowercase UUID form. turnzero deploy --origin https://dev.turnzero.ai and turnzero check --origin https://dev.turnzero.ai refuse a folder whose manifest names another application.

Keep the application paths shown in the table. The download URLs end in .txt so a browser reads the code instead of running it; that suffix is not part of the application filename. Each file is also reproduced below for tools reading this page through MCP.

Without a shell, use exact version 8.22.0 for pg: replace "^8.22.0" with "8.22.0" in package.json's dependencies. This version is published, so no registry lookup is needed for this sample. Only the direct dependency is pinned. Keeping a range also builds, but without a lockfile the build resolves it again each time.

For a new application, make these calls in order.

  1. Call tzcloud_create_application with name and kind: "serverless", without size. Keep its returned application.id for later calls.
  2. Call tzcloud_submit_manifest with application and the complete manifest object.
  3. Call read_rate_card and explain the expected usage charges before deploying. Follow the manifest answer’s cost guidance.
  4. Call tzcloud_deploy_files with application, environment: "production" and the complete files list of path and content. Use pg version 8.22.0.
  5. If the deploy is still running, call tzcloud_read_status with application and wait_seconds: 45 until it ends. Read the outcome; stop if it failed.

Check it works #

Call tzcloud_check_deploy with application. For the other calls below, pass that application ID and environment: "production". For JSON writes, set headers to {"content-type":"application/json"} and pass the JSON text as body.

  • Use tzcloud_request_route for / and /api/notes; expect 200 for each. The latter returns a JSON object whose notes member is a list.
  • Call tzcloud_write_route with method: "POST", path: "/api/notes" and body containing {"title":"check"}. Expect 201; keep the returned note’s ID.
  • Read /api/notes again and check that notes contains that ID.
  • Send a blank title with the same POST; expect 400 invalid_request.
  • Call tzcloud_read_logs with source: "pool" and check for errors.
  • Report the results and the test note left behind. This example has no delete route.

These calls do not run the local tests under test/ or check the page in a browser. Tell the person what these checks leave untested and who can read and write, as described above.

Files #

Paths are relative to the application root—the folder containing package.json. deploy_files uses these paths without an app/ prefix.

Application path Read source
.gitignore Text
AGENTS.md Text
client/app.js Text
client/index.html Text
client/styles.css Text
functions/api/notes.js Text
lib/db.js Text
lib/notes.js Text
manifest.json Text
migrations/0001_notes.sql Text
package.json Text
test/notes.test.mjs Text

File contents #

.gitignore #

node_modules/
.env
.env.*

AGENTS.md #

# This service runs on Turn Zero Cloud

The service in this folder is hosted on Turn Zero Cloud. It started from the platform's `functions-database` template: a notes page with a function and a database, served as a serverless application. This file describes the template the service started from: keep it current as the service changes.

## Where you build

- Edit the page's files under `client/`. A file's path below `client/` is its path on the site; `/` serves `client/index.html`.
- Each file under `functions/` is one function. `functions/api/notes.js` handles `/api/notes` and the paths beneath it.
- Put shared code under `lib/`, which serves no path.
- Put each database schema change in a new file under `migrations/`. The platform applies these files before a deployed version serves. `turnzero run --origin https://dev.turnzero.ai` applies them to the database `APP_DATABASE_URL` names before it serves the folder's functions.

## Where the rules are

Your AI coding tool reads Turn Zero Cloud's rules through the `turnzero` MCP server. That connection gives the tool access to the products on your account. Read the current rules there because they change with the platform.

- Where the server is not connected, set up Turn Zero Cloud first: https://dev.turnzero.ai/cloud/getting-started/set-up/
- Before you change or deploy this service, read the server's `deploy` skill.

## What you run here

- The tests: `npm test`, in this folder.
- A deploy: the `deploy` skill gives each step and the line to run, in this order: `tzcloud_submit_manifest`, `tzcloud_deploy_command`.

client/app.js #

// client/app.js: the page's script. It calls the function at /api/notes on
// the page's own address.
const list = document.getElementById('notes');
const status = document.getElementById('status');
const form = document.getElementById('add');
const title = document.getElementById('title');

function show(notes) {
  list.replaceChildren(
    ...notes.map((note) => {
      const item = document.createElement('li');
      item.textContent = note.title;
      return item;
    }),
  );
  status.textContent = notes.length === 0 ? 'No notes yet.' : '';
}

async function load() {
  const response = await fetch('/api/notes');
  if (!response.ok) throw new Error('The notes could not be read.');
  show((await response.json()).notes);
}

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  status.textContent = '';
  try {
    const response = await fetch('/api/notes', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: title.value }) });
    if (!response.ok) throw new Error('The note could not be added.');
    title.value = '';
    await load();
  } catch (error) {
    status.textContent = error.message;
  }
});

load().catch((error) => {
  status.textContent = error.message;
});

client/index.html #

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Notes</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <main>
    <h1>Notes</h1>
    <p>Turn Zero Cloud serves this page from <code>client/index.html</code>. The function in <code>functions/api/notes.js</code> stores notes in the application's database.</p>
    <form id="add">
      <label for="title">A new note</label>
      <input id="title" name="title" maxlength="200" required>
      <button type="submit">Add</button>
    </form>
    <p id="status" role="status" aria-live="polite"></p>
    <ul id="notes"></ul>
  </main>
  <script src="app.js"></script>
</body>
</html>

client/styles.css #

/* client/styles.css, which client/index.html links beside it */
:root {
  color-scheme: light dark;
  font-family: system-ui, sans-serif;
  line-height: 1.5;
}

body {
  margin: 0 auto;
  max-width: 40rem;
  padding: 2rem 1rem;
}

h1 {
  font-size: 1.75rem;
  margin: 0 0 1rem;
}

code {
  font-family: ui-monospace, monospace;
}

form {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: center;
  margin: 1.5rem 0 0.5rem;
}

input {
  flex: 1 1 12rem;
  font: inherit;
  padding: 0.4rem 0.5rem;
}

button {
  font: inherit;
  padding: 0.4rem 0.9rem;
}

ul {
  padding-left: 1.25rem;
}

functions/api/notes.js #

// functions/api/notes.js: this file answers /api/notes and the paths beneath
// it. A function is a module whose default export has fetch(request) and
// returns a Response.
import { notesStore } from '../../lib/db.js';
import { createNotesApi } from '../../lib/notes.js';

export default { fetch: createNotesApi(notesStore) };

lib/db.js #

// lib/db.js: the notes' store in the application's database.
import pg from 'pg';

// One connection for this worker, opened at its first query and kept while
// the worker lives. The platform supplies APP_DATABASE_URL, and the turnzero
// command's provision writes it for a local run.
let pool;

function database() {
  const url = process.env.APP_DATABASE_URL;
  if (!url) throw new Error('APP_DATABASE_URL is not set');
  pool ??= new pg.Pool({ connectionString: url, max: 1, connectionTimeoutMillis: 5000 }).on('error', (error) => console.error(error.message));
  return pool;
}

// The platform applies the files under migrations/ before a version serves,
// so the table stands when a function first reads it.
export const notesStore = {
  async addNote(title) {
    const { rows } = await database().query('INSERT INTO "notes" (title) VALUES ($1) RETURNING id, title', [title]);
    return rows[0];
  },
  async listNotes() {
    const { rows } = await database().query('SELECT id, title FROM "notes" ORDER BY id');
    return rows;
  },
};

lib/notes.js #

// lib/notes.js: the notes API over any store. Code under lib/ is shared by the
// functions and answers no path. functions/api/notes.js gives this API the
// database's store, and the tests give it a double.

const json = (body, status = 200, headers = {}) =>
  new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers } });

// The page's input has the same bound. The function checks it too, since a
// request need not come from the page.
const TITLE_MAX = 200;

// GET lists the notes, oldest first. POST adds one from { "title": "..." }.
export function createNotesApi(store) {
  return async function fetch(request) {
    if (request.method === 'GET') return json({ notes: await store.listNotes() });
    if (request.method === 'POST') {
      let sent;
      try {
        sent = await request.json();
      } catch {
        sent = null;
      }
      const title = typeof sent?.title === 'string' ? sent.title.trim() : '';
      if (title === '' || title.length > TITLE_MAX) return json({ error: 'invalid_request', detail: `Send a JSON object with a title of 1 to ${TITLE_MAX} characters.` }, 400);
      const note = await store.addNote(title);
      // A function's console lines reach the application's logs.
      console.log(`note ${note.id} added`);
      return json(note, 201);
    }
    return json({ error: 'method_not_allowed', detail: 'This path takes GET and POST.' }, 405, { allow: 'GET, POST' });
  };
}

manifest.json #

{
  "manifest_version": 1,
  "services": [{ "kind": "database" }],
  "region": "usa",
  "egress": [],
  "audience": { "kind": "public" },
  "packages": []
}

migrations/0001_notes.sql #

-- migrations/0001_notes.sql
CREATE TABLE "notes" (
  id bigserial PRIMARY KEY,
  title text NOT NULL CHECK (title <> '')
);

package.json #

{
  "name": "notes-functions",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --test"
  },
  "dependencies": {
    "pg": "^8.22.0"
  }
}

test/notes.test.mjs #

// test/notes.test.mjs: the notes API over a store double, with no database.
import assert from 'node:assert/strict';
import test from 'node:test';
import { createNotesApi } from '../lib/notes.js';

function double() {
  const notes = [];
  return {
    async addNote(title) {
      const note = { id: String(notes.length + 1), title };
      notes.push(note);
      return note;
    },
    async listNotes() {
      return [...notes];
    },
  };
}

const ADDRESS = 'http://localhost/api/notes';
const post = (body) => new Request(ADDRESS, { method: 'POST', headers: { 'content-type': 'application/json' }, body });

test('POST adds a note and GET lists it', async () => {
  const api = createNotesApi(double());
  const added = await api(post(JSON.stringify({ title: ' first ' })));
  assert.equal(added.status, 201);
  assert.deepEqual(await added.json(), { id: '1', title: 'first' });
  const listed = await api(new Request(ADDRESS));
  assert.equal(listed.status, 200);
  assert.deepEqual(await listed.json(), { notes: [{ id: '1', title: 'first' }] });
});

test('a POST with no title, or with no JSON, returns 400 invalid_request and adds nothing', async () => {
  const store = double();
  const api = createNotesApi(store);
  for (const body of [JSON.stringify({ title: '  ' }), JSON.stringify({}), 'not json']) {
    const refused = await api(post(body));
    assert.equal(refused.status, 400);
    assert.equal((await refused.json()).error, 'invalid_request');
  }
  assert.deepEqual(await store.listNotes(), []);
});

test('a POST with a title longer than 200 characters returns 400 invalid_request and adds nothing', async () => {
  const store = double();
  const api = createNotesApi(store);
  const refused = await api(post(JSON.stringify({ title: 'a'.repeat(201) })));
  assert.equal(refused.status, 400);
  assert.equal((await refused.json()).error, 'invalid_request');
  assert.deepEqual(await store.listNotes(), []);
  const added = await api(post(JSON.stringify({ title: 'a'.repeat(200) })));
  assert.equal(added.status, 201);
});

test('another method returns 405 method_not_allowed', async () => {
  const refused = await createNotesApi(double())(new Request(ADDRESS, { method: 'DELETE' }));
  assert.equal(refused.status, 405);
  assert.equal(refused.headers.get('allow'), 'GET, POST');
  assert.equal((await refused.json()).error, 'method_not_allowed');
});