Read and write records
What you will do
You will build a notes page that creates, reads, changes and deletes the user's notes, and shows whether each change has reached the server yet.
A few words used on this page:
- An app is the web app you build. A user is the person who uses it; the notes belong to them, in their own private database on the server.
- A collection is one kind of data, here notes, and each saved note is a record. The collection's schema lists its fields; the server checks every record against it.
- The SDK (
@phibac/sdk) is the JavaScript library your page uses. It keeps a copy of the user's records in the browser, so reads are instant and writes work offline. - An rkey (record key) is the ID of a record within its collection. The SDK makes it when your app creates the record, and you pass it to
get,updateanddelete.
Before you start
You need the notes app from Build your first app up to step 7: the local server running, the com.example.notes.note collection published, and src/pb-types.ts generated. To learn more about signing in, see Sign users in.
Steps
1. Check the generated types
src/pb-types.ts, written by npx phibac generate, holds the note type. For the quickstart's collection it is:
// Generated from published collection schemas. Do not edit by hand.
/** A note written by the user */
export interface ComExampleNotesNoteV1 {
/** Whether the note is pinned */
pinned?: boolean;
/** Note text */
text: string;
}
export const SCHEMA_MAJORS = {
"com.example.notes.note": 1,
} as const;
2. Write the page
Create index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Notes</title>
</head>
<body>
<button type="button" id="sign-in">Sign in</button>
<p id="message" role="alert"></p>
<form id="note-form" hidden>
<input id="note-text" placeholder="Write a note" aria-label="Note text" />
<button type="submit">Add note</button>
</form>
<ul id="note-list"></ul>
<button type="button" id="show-all" hidden>Show all notes as text</button>
<pre id="all-notes"></pre>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
3. Write the code
Create src/main.ts, with your app ID in place of app_...:
import { connect, PbError, type Collection, type PbRecord } from "@phibac/sdk";
import { SCHEMA_MAJORS, type ComExampleNotesNoteV1 as Note } from "./pb-types";
const APP = "app_...";
const BASE_URL = "http://localhost:8787";
const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;
const form = document.querySelector<HTMLFormElement>("#note-form")!;
const noteText = document.querySelector<HTMLInputElement>("#note-text")!;
const list = document.querySelector<HTMLUListElement>("#note-list")!;
const showAll = document.querySelector<HTMLButtonElement>("#show-all")!;
const allNotes = document.querySelector<HTMLPreElement>("#all-notes")!;
let notes: Collection<Note> | null = null;
// Shows an error's code and message. textContent never runs text as HTML.
function showError(e: unknown): void {
message.textContent = e instanceof PbError ? `${e.code}: ${e.message}` : String(e);
}
function button(label: string, onClick: () => Promise<void>): HTMLButtonElement {
const b = document.createElement("button");
b.type = "button";
b.textContent = label;
b.addEventListener("click", () => onClick().catch(showError));
return b;
}
// One list item per note: its text, its status and three buttons.
function show(records: PbRecord<Note>[]): void {
list.replaceChildren(
...records.map((record) => {
const item = document.createElement("li");
const label = document.createElement("span");
label.textContent = `${record.data.pinned ? "[pinned] " : ""}${record.data.text} (${record.status})`;
item.append(
label,
button("Edit", () => editNote(record.rkey)),
button(record.data.pinned ? "Unpin" : "Pin", () => togglePin(record)),
button("Delete", () => notes!.delete(record.rkey)),
);
return item;
}),
);
}
// get() reads one note by its rkey; update() changes only the fields you pass.
async function editNote(rkey: string): Promise<void> {
const current = await notes!.get(rkey);
if (current === null) {
message.textContent = "That note no longer exists.";
return;
}
const text = prompt("Edit the note", current.data.text);
if (text === null || text.trim() === "") return;
await notes!.update(rkey, { text: text.trim() });
}
// Pinning sets pinned to true. Unpinning removes the field: null removes a field.
// The generated type has no null in it, so the patch is cast to tell TypeScript this is meant.
async function togglePin(record: PbRecord<Note>): Promise<void> {
if (record.data.pinned) {
await notes!.update(record.rkey, { pinned: null } as unknown as Partial<Note>);
} else {
await notes!.update(record.rkey, { pinned: true });
}
}
signIn.addEventListener("click", async () => {
try {
const backend = await connect({ app: APP, baseUrl: BASE_URL, schemaMajors: SCHEMA_MAJORS });
notes = backend.collection<Note>("com.example.notes.note");
// Calls show() now, and again whenever a note changes.
notes.subscribe(show);
// Called when the server refuses a change for good; the change is dropped.
backend.onConflict(({ error }) => showError(error));
signIn.hidden = true;
form.hidden = false;
showAll.hidden = false;
} catch (e) {
showError(e);
}
});
// create() saves a new note and returns it at once, with status "pending".
form.addEventListener("submit", async (event) => {
event.preventDefault();
const text = noteText.value.trim();
if (notes === null || text === "") return;
try {
const record = await notes.create({ text });
console.log("created", record.rkey, record.status);
form.reset();
} catch (e) {
showError(e);
}
});
// list() returns every note in the browser's copy, oldest first.
showAll.addEventListener("click", async () => {
if (notes === null) return;
try {
const all = await notes.list();
allNotes.textContent = all.map((r) => `${r.createdAt} ${r.data.text}`).join("\n");
} catch (e) {
showError(e);
}
});
Start Vite on the origin you registered (npx vite --port 5173 --strictPort), open http://localhost:5173 and press Sign in. The steps below explain each call; SDK reference lists every method of a collection.
4. Create a record
notes.create({ text }) saves a new note. It does not wait for the server: the SDK makes the rkey, saves the note in the browser's copy, queues it to be sent and returns the new record at once. The record looks like this:
| Property | What it is |
|---|---|
id |
The record's global ID, pb://<userId>/<collection>/<rkey>. A recordRef field holds this value. |
collection, rkey |
The collection's name and the record's key. |
data |
The fields, such as { text: "Buy milk" }. |
rev |
A number that goes up with every change the server makes to the record; 0 for a record the server does not have yet. |
status |
pending until the server has the latest change, then synced. |
createdAt, updatedAt |
When the record was created and last changed, as date-and-time strings. |
create() needs a plain object; anything else fails at once with invalid_request. The server checks the record against the schema only when it receives it. If it refuses the record (for example schema_violation for a missing required field), the SDK drops the change, removes the note from the browser's copy and calls the function you gave backend.onConflict(). The generated types catch most such mistakes before you run the code.
5. Read one record
notes.get(rkey) returns the record, or null if there is none. It reads the browser's copy at once and never waits for the network. The first time your app uses a collection after connect(), the SDK brings that copy up to date from the server in the background, so right after signing in on a new device a record can still be missing. Use subscribe() to be told when it arrives.
6. Read every record
notes.list() returns every record in the browser's copy, oldest first, with no limit. Like get(), it answers at once from the copy. To choose, sort or limit the records, use a query (see Query, sort and live updates).
notes.subscribe(show) calls show with every record now, and again whenever any of them changes: after your own writes, when the server confirms them, and when a change arrives from another tab or device. It returns a function that stops the calls. This page uses it to keep the list up to date.
7. Update a record
notes.update(rkey, { text }) changes a record. The update is a shallow merge: the fields you pass replace those fields, and every other field keeps its value. "Shallow" means a field is replaced whole: if a field holds an object or a list, pass the complete new value.
Setting a field to null removes it from the record, as Unpin does with pinned. The types npx phibac generate writes do not allow null, so TypeScript needs the cast shown in togglePin. Do not use { pinned: undefined } instead: it compiles, but a field set to undefined is left out of the change, so nothing is removed. Removing a required field is refused by the server with schema_violation.
Like create(), update() returns the changed record at once with status pending. It fails at once with not_found if there is no record with that rkey, and with record_deleted if the record was deleted.
8. Delete a record
notes.delete(rkey) deletes a record. It returns at once and the record disappears from get(), list() and live lists straight away. Deleting a record this browser already knows is deleted does nothing. If this browser has no copy of the record, the SDK first asks the server for the collection's latest changes: a record deleted elsewhere then fails with record_deleted, and an rkey that never existed fails with not_found.
A deleted record's key cannot be used again: writing to it fails with record_deleted, so save the data as a new record instead. The deleted version is kept in the record's history for 30 days, and the user can restore it from their account area. Your app cannot read the history.
9. Show the status
Every record has a status: pending while the browser has a change the server has not confirmed, then synced. This page shows it next to each note. For the whole app, backend.status() returns online (whether the server is reachable) and pending (how many changes are waiting). Offline writes and sync explains what happens to waiting changes and when two devices change the same record.
What you should see
- After Sign in, the list shows the notes you already have.
- Type a note and press Add note. It appears at once, marked
(pending), then(synced). The browser's console shows its new rkey. - Press Pin: the note shows
[pinned]. Press Unpin: the mark goes away, because thepinnedfield was removed. - Press Edit, change the text and press OK. Only the text changes; a pinned note stays pinned.
- Press Delete. The note disappears at once.
- Press Show all notes as text to see every note, oldest first.
- Switch the browser to offline in its developer tools and add, change or delete notes. Each change shows at once and stays
(pending)until you switch back online.
Common problems
not_foundfromupdate()ordelete(). There is no record with that rkey in this collection. Check the rkey and the collection name.record_deleted. The record was deleted, perhaps on another device. Create a new record instead.schema_violationin theonConflictfunction. The server refused the record: itsfieldslist names each field and the reason, such asrequiredorunknown field. The change was dropped; fix the data and save it again.not_foundin theonConflictfunction, saying the collection "has no published schema". Runnpx phibac deployto publish the collection, then try again.forbiddenin theonConflictfunction. Your app wrote to a collection another app owns. An app can write only its own collections and its ownsandbox.collections; other apps' collections are read-only.invalid_requestfromcreate()orupdate(). You passed something that is not a plain object. Pass the fields as an object, such as{ text: "hi" }.- TypeScript says
nullis not allowed inupdate(). The generated types do not includenull. Cast the patch astogglePindoes. get()returnsnullfor a record that exists. The browser's copy has not caught up with the server yet. Subscribe to the collection and read it again when your function is called.unauthorized. The user is signed out or their sign-in expired. Callconnect()again from a click (see Sign users in).
Next step
Query, sort and live updates shows how to choose, sort and limit the records you show, and what queries cannot do.