functions-app example #
On this page
A notes page with a function and a database, served as a serverless application.
These files come from the same source as the scaffold command. They are the starter files before the command installs dependencies.
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 --template functions-app
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. The copied AGENTS.md instructions below use the names listed by the MCP connection.
Follow Deploying from a chat. Create a serverless application and submit its manifest with submit_manifest before the first deploy. Read the files below and send the application files through deploy_files.
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 and turnzero check 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.
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-app` 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. A local run reads development's database, so it reads a new table only after a deploy to development, an environment you add only where the owner asks. Until then a function that reads the table fails in a local run, so `npm test` is the local check.
## Where the rules are
Turn Zero Cloud serves its rules to a coding tool through the MCP server `turnzero`, one connection to the products your account holds. The rules change with the platform, so none is repeated here.
- Where the server is not connected, set up Turn Zero Cloud first: https://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 });
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');
});