docs: correct KV and events recipes against current behavior

Fixes code that failed or did the wrong thing, and statements that no
longer matched the SDK and backend, across 15 recipes.
This commit is contained in:
Daniel Salazar committed 2026-11-26 00:09:47 -07:00
1 parent 881c311a58
commit c9e2dc9986
15 files changed
+141 -71

No files matched your search

+21 -11
View File
@@ -119,10 +119,13 @@ const openRoom = ({ prefix = '', handle }) => {
};
};
// The creator opens the room by its prefix, and a member by their share's handle.
const room = handle ? openRoom({ handle }) : openRoom({ prefix });
// The creator opens the room by its prefix.
const room = openRoom({ prefix });
```
A member opens the same room with `openRoom({ handle })`, using the `handle` of
their share.
## Send a Message
Give each message its own key, made from the time and a random part:
@@ -166,16 +169,22 @@ Subscribe to the room's messages with the helper's `watch()`, which uses
people with the chat open, so a subscription that ends with the page is enough:
```js
await room.watch('msg:*', (event) => {
await room.watch('msg:*', async (event) => {
if (event.op === 'gap') return reloadMessages();
if (event.op === 'set') showMessage(event.key, event.value);
if (event.op === 'del') removeMessage(event.key);
if (event.op === 'del') return removeMessage(event.key);
if (event.op === 'set') {
showMessage(event.key, 'value' in event ? event.value : await room.get(event.key));
}
});
```
Every message arrives this way, including the sender's own, so sending doesn't
need to draw anything. A `gap` event means some messages weren't delivered, for
example during a reconnect, so load the latest page again.
example during a reconnect, so load the latest page again. An event sometimes
arrives without its value, for example for a very long message, and the handler
then reads the message with `room.get()`.
[Getting the new value](/Events/subjects/#getting-the-new-value) lists the
cases.
## Remove a Member or Leave the Room
@@ -352,8 +361,7 @@ const openRoom = ({ prefix = '', handle }) => {
};
};
// The creator opens the room by its prefix, and a member by their share's handle.
const room = handle ? openRoom({ handle }) : openRoom({ prefix });
const room = openRoom({ prefix }); // a member: openRoom({ handle })
const user = await puter.auth.getUser();
const sendMessage = (text) => room.set(
@@ -364,9 +372,11 @@ const sendMessage = (text) => room.set(
const page = await room.latest('msg:*');
showMessages(page.items.reverse());
await room.watch('msg:*', (event) => {
await room.watch('msg:*', async (event) => {
if (event.op === 'gap') return reloadMessages();
if (event.op === 'set') showMessage(event.key, event.value);
if (event.op === 'del') removeMessage(event.key);
if (event.op === 'del') return removeMessage(event.key);
if (event.op === 'set') {
showMessage(event.key, 'value' in event ? event.value : await room.get(event.key));
}
});
```
@@ -109,7 +109,7 @@ async function loadCart () {
}
const { lines, total } = await loadCart();
const totalText = (total / 100).toFixed(2); // '60.00'
const totalText = (total / 100).toFixed(2); // '44.00'
```
The filter also skips a product with only some of its fields, which is left
+7 -4
View File
@@ -42,7 +42,7 @@ router.get('/me', async ({ user }) => {
});
```
Each HTTP verb has its own method, such as
GET, POST, PUT, DELETE and OPTIONS each have their own method, such as
[`router.post()`](/Workers/router/#http-methods) and
[`router.delete()`](/Workers/router/#http-methods).
@@ -100,7 +100,9 @@ router.get('/notes/:id', async ({ params, user }) => {
```
Captured values are always strings, so convert them yourself when you need a
number.
number. They're still URL-encoded, so a space arrives as `%20`. Decode a value
that can contain spaces or other special characters with
[`decodeURIComponent()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent).
Query strings are not part of the path. To read one, parse the request URL:
@@ -190,10 +192,11 @@ third-party response before your app sees it:
```js
router.get('/weather/:city', async ({ params }) => {
const res = await fetch(`https://wttr.in/${encodeURIComponent(params.city)}?format=j1`);
const city = decodeURIComponent(params.city);
const res = await fetch(`https://wttr.in/${encodeURIComponent(city)}?format=j1`);
const data = await res.json();
return { city: params.city, tempC: data.current_condition[0].temp_C };
return { city, tempC: data.current_condition[0].temp_C };
});
```
@@ -31,20 +31,22 @@ To show notifications as they arrive, subscribe to `notif:app-user` with
```js
const sub = await puter.events.onLocal('notif:app-user', ({ event }) => {
if (event.op === 'gap') return;
if (event.op !== 'post') return;
showNotification(event);
});
```
A gap carries no notification, so this handler skips it.
A new notification has `op: 'post'`. A gap carries no notification, and neither
does the `dismiss` event sent when the user dismisses one, so this handler
skips both.
[Catch Up, Then Keep Listening](#catch-up-then-keep-listening) handles gaps
properly. The fields to use are:
- `id`, the notification's ID. A notification has the same `id` whether it
arrives live or from [`fetch()`](/Events/fetch/).
- `type`, what kind of notification it is, such as `app.events.ended`.
- `notification.title`, the text to show. The other fields in `notification`
depend on the type.
- `notification.title`, the text to show. A `kv.share.received` notification
has a `label` instead. The other fields in `notification` depend on the type.
- `ts`, when it was created, in milliseconds since the epoch.
- `replaced`, `true` when your app's notification replaced an earlier one in
its [group](/Notifications/notify/#groups). It keeps the earlier `id`, and its
@@ -137,19 +139,22 @@ async function catchUp () {
await save();
}
await puter.events.onLocal(subject, async ({ event }) => {
if (event.op === 'gap') return catchUp();
showOnce(event);
await save();
await puter.events.onLocal(subject, ({ event }) => {
if (event.op === 'dismiss') return;
return catchUp();
});
await catchUp();
```
Subscribe first, then fetch, so a notification created while `catchUp()` runs
still reaches the handler. A notification can then arrive both live and from
[`fetch()`](/Events/fetch/), and `showOnce()` drops the second copy. A
replacement has the same `ts` on both copies, so `showOnce()` keys it on `id`
and `ts` and shows each replacement once.
Notifications sent within 250 ms of each other arrive as one event, the last
of them. So the handler doesn't show the event it gets. It calls `catchUp()`,
which reads every notification since the saved cursor.
Subscribe first, then fetch, so a notification created while the first
`catchUp()` runs starts another one. The same notification can then come back
from two reads, and `showOnce()` drops the second copy. A replacement has the
same `ts` on every copy, so `showOnce()` keys it on `id` and `ts` and shows
each replacement once.
The last page has no cursor, so the saved cursor stays on the page before it,
and the next visit reads that page again. That's why the IDs are saved along
@@ -163,7 +168,7 @@ was closed comes back with `replaced` set and its new `ts`, and `showOnce()`
shows it.
A [gap](/recipes/watch-for-changes/#handle-gaps) means notifications weren't
delivered, and one also arrives after a reconnect. Calling `catchUp()` on a gap
reads what was missed, and `showOnce()` skips the rest. The subscription tells
you when something new arrives, so there's no need to call
[`fetch()`](/Events/fetch/) on a timer.
delivered, and one also arrives after a reconnect. The handler calls
`catchUp()` for a gap too, which reads what was missed, and `showOnce()` skips
the rest. The subscription tells you when something new arrives, so there's no
need to call [`fetch()`](/Events/fetch/) on a timer.
+2 -2
View File
@@ -12,8 +12,8 @@ checks, HTTP errors and connection failures.
This example checks a site when the user clicks a button, keeps each result
for seven days, and shows the latest 20 checks. Each user's history lives in
their own account. The first check opens the Puter sign-in window if the user
isn't signed in yet.
their own account. Loading the history opens the Puter sign-in window if the
user isn't signed in yet.
## Check the Site
@@ -93,10 +93,15 @@ holds and end the scope, pass the app's uid to
[`puter.events.workers.destroy()`](/Events/workers/) with `scope: 'user'`:
```js
await puter.events.workers.destroy(puter.appID, { scope: 'user' });
const held = await puter.events.handlers.list({ scope: 'user' });
if (held.length > 0) {
await puter.events.workers.destroy(puter.appID, { scope: 'user' });
}
```
Do this after you've ended the subscriptions and schedules that use it, with
A scope that holds no handlers has nothing to remove, and
[`workers.destroy()`](/Events/workers/) rejects for it with
`events_handler_not_found`, so the code checks first. Do this after you've ended the subscriptions and schedules that use it, with
`unsubscribe()` and `removeSchedule()`. Listing and removing don't need credit,
and [`workers.list()`](/Events/workers/) shows the user's scopes with
`scope: 'user'`.
+5 -2
View File
@@ -44,8 +44,11 @@ async function saveNote (noteId, text) {
```
[`puter.kv.incr()`](/KV/incr/) gives every save its own number, even when two
tabs save at once. The number is padded with zeros so the keys sort in order
(otherwise `10` would come before `9`).
tabs save at once. Two saves at nearly the same moment from different places,
such as two devices far apart, can still get the same number, as
[`puter.kv.set()`](/KV/set/#writing-only-if-absent) explains for `onlyIfAbsent`.
One copy then replaces the other in the history. The number is padded with
zeros so the keys sort in order (otherwise `10` would come before `9`).
Passing an array to [`puter.kv.set()`](/KV/set/) writes both keys in one
request. The copy gets an `expireAt`, a Unix time in seconds, so it's deleted
@@ -166,11 +166,19 @@ async function update() {
render(people);
}
await puter.events.onLocal(`fs:${root}/.presence`, async () => {
const presence = await puter.fs.mkdir(`${root}/.presence`, { createMissingParents: true });
await puter.events.onLocal(`fs:${presence.uid}`, async () => {
if (currentFileId) await update();
});
```
The subject names the `.presence` folder by its `uid`. A subject can't use the
path that [`puter.fs.listShared()`](/FS/listShared/) gives for a shared folder,
and that subscription is rejected with `subject_does_not_exist`. The
[`puter.fs.mkdir()`](/FS/mkdir/) call returns the folder when it already
exists, and creates it otherwise.
The handler runs for this tab's own writes and for the person's other tabs too,
since those change the list as well. It reads the whole folder instead of using
what the event says, so a [gap](/recipes/watch-for-changes/#handle-gaps) marker,
@@ -361,7 +369,9 @@ async function closeFile() {
currentFileId = null;
}
await puter.events.onLocal(`fs:${root}/.presence`, async () => {
const presence = await puter.fs.mkdir(`${root}/.presence`, { createMissingParents: true });
await puter.events.onLocal(`fs:${presence.uid}`, async () => {
if (currentFileId) await update();
});
```
@@ -81,7 +81,9 @@ errors.
The notification names your app, not the sender, so the title says who wrote
the message. The `group` makes a new message replace the member's notification
for the same room instead of adding another, so a busy room doesn't use up the
daily notification limit.
member's daily notification limit. Notifications sent through a share also have
a [limit of their own](/rate-limits-and-quotas/#notifications) for each sender
and recipient, and every message counts toward it.
## Say What a Push Shows
@@ -208,8 +210,10 @@ explains handlers in more detail:
```js
await puter.events.handlers.publish('notifyNewMessage', async ({ event, user, ctx }) => {
const message = event.value;
if (event.op !== 'set' || !message || message.from === ctx.me) return;
if (event.op !== 'set') return;
const options = ctx.handle ? { handle: ctx.handle } : undefined;
const message = 'value' in event ? event.value : await user.kv.get(event.key, options);
if (!message || message.from === ctx.me) return;
await user.notifications.notify({
title: `${message.from} in ${ctx.roomTitle}`.slice(0, 120),
@@ -244,12 +248,15 @@ async function subscribeToRoom () {
subject,
handlerName: 'notifyNewMessage',
includeValue: true,
context: { me: user.username, roomId, roomTitle: title },
context: { me: user.username, roomId, roomTitle: title, handle },
});
return true;
}
```
The `me` check in the handler skips the member's own messages. When the creator
The `me` check in the handler skips the member's own messages. An event
sometimes arrives without its value, for example for a very long message, so
the handler then reads the message itself, through the member's `handle` from
the `context`. When the creator
removes a member, or the member leaves, the member's subscription stops on its
own.
@@ -94,11 +94,11 @@ await puter.events.onSchedule({
Create it once per user. [Run Code on a Schedule](/recipes/run-code-on-a-schedule/#create-the-schedule-once-per-user)
shows how to check [`listSchedules()`](/Events/listSchedules/) first.
The `context` is stored with the schedule and can't be changed. When the
user's key changes, remove the schedule with
[`puter.events.removeSchedule()`](/Events/removeSchedule/) and create a new
one. The [`listSchedules()`](/Events/listSchedules/) method shows the names
of the `context` keys, never their values.
The `context` is stored with the schedule. When the user's key changes,
replace the whole `context` with
[`puter.events.updateSchedule(scheduleId, { context })`](/Events/updateSchedule/).
The [`listSchedules()`](/Events/listSchedules/) method shows the names of the
`context` keys, never their values.
The schedule runs every 15 minutes from when it's created, which is as often
as a free plan allows. A paid plan can run one every minute. See
@@ -158,7 +158,9 @@ A few details:
every run would fail at the same page.
- The extra run is a one-time schedule with the same handler and the same
`context`, plus `followUp: true`. It continues from the saved cursor and
ends on its own after it runs.
ends on its own after it runs. It finds the handler by its published name,
so this version needs the published handler. A handler passed inline has no
name to bind to, and the call rejects with `events_handler_not_found`.
- An extra run doesn't schedule another one. Whatever it leaves over, the
next 15-minute run picks up. A schedule created from a handler counts as
one step deeper in a [handler chain](/Events/onPersistent/#handlers-that-trigger-handlers),
@@ -187,17 +187,24 @@ If two tabs open at the same moment, both might create a subscription. When
[`list()`](/Events/list/) returns more than one match, keep one and unsubscribe
the rest.
With `queue: true`, Puter treats the subscription like a work queue, so every
new file gets recorded. A run that fails with a network error, a timeout or
another temporary error is retried after 2 seconds, then 4, then 8, up to 5
minutes apart. Runs over the per-minute limit for your app wait and run later.
With `queue: true`, Puter treats the subscription like a work queue. A run
that fails with a network error, a timeout or another temporary error is
retried after 2 seconds, then 4, then 8, up to 5 minutes apart. Runs over the
per-minute limit for your app wait and run later.
Without `queue`, a failed run isn't retried and runs over the limit are
skipped, so uploading 100 files at once would record only about 60.
A queue also takes a [limited number of events a minute](/rate-limits-and-quotas/#delivery).
Events past that are replaced by a [gap](/recipes/watch-for-changes/#handle-gaps),
which this handler skips. If users can add several hundred files at once, list
the folder with [`user.fs.readdir()`](/FS/readdir/) when the handler gets a
gap, and record what's missing.
Queued events cost more per event, as
[What events cost](/rate-limits-and-quotas/#what-events-cost) lists. For work
where a missed event doesn't matter, such as refreshing a summary that the next
change refreshes anyway, leave `queue` out.
change refreshes anyway, leave `queue` out. To queue work your app starts
itself and show its progress, see [Build a Job Queue](/recipes/build-a-job-queue/).
## Pass Settings to the Handler
@@ -172,18 +172,22 @@ The helper's `watch()` calls [`puter.events.onLocal()`](/Events/onLocal/), so
each person sees the other's changes while the list is open:
```js
await alicesList.watch('item:*', (event) => {
await alicesList.watch('item:*', async (event) => {
if (event.op === 'gap') return reloadList();
if (event.self && !event.viaWorker) return;
if (event.op === 'del') removeItem(event.key);
else showItem(event.key, event.value);
if (event.op === 'del') return removeItem(event.key);
if (event.op === 'set') {
showItem(event.key, 'value' in event ? event.value : await alicesList.get(event.key));
}
});
```
The `self` check skips the user's own writes, which your app already shows, but
not changes a worker made as them, which have `viaWorker` set. A `gap` event
means some changes weren't delivered, for example during a reconnect, so reload
the list. [The event](/Events/subjects/#the-event) lists every field.
the list. An event sometimes arrives without its value, and the handler then
reads the item with `get()`. [The event](/Events/subjects/#the-event) lists
every field.
For Dan, `watch()` puts your app's id from [`puter.appID`](/Utils/appID/) in the
subject, since a `kv:` subject for a key that contains `:` needs it, as
@@ -192,6 +196,9 @@ change the same item at about the same time, the last write wins.
## Next Steps
- To keep both changes when two people change the same value at once, such as
a count, see
[Combine Changes From Several Users](/recipes/combine-changes-from-several-users/).
- To keep some entries in the prefix private, see
[Share Only Part of the Data](/recipes/let-someone-view-your-data/#share-only-part-of-the-data).
- To let each person change only their own items, give each one a part of the
+5 -2
View File
@@ -64,8 +64,11 @@ async function addMessage (chatId, text) {
```
[`puter.kv.incr()`](/KV/incr/) gives every message its own number, even if two
tabs send at the same moment, so a shard never gets more than 50 messages. The
zero padding keeps the shard keys in order when they're listed.
tabs send at the same moment, so a shard doesn't get more than 50 messages. Two
calls at nearly the same moment from different places, such as two devices far
apart, can still get the same number, as
[`puter.kv.set()`](/KV/set/#writing-only-if-absent) explains for `onlyIfAbsent`.
The zero padding keeps the shard keys in order when they're listed.
Aim for shards of about 10 to 50 KB, and cap how long a message can be, so 50
messages can't grow bigger than you planned. The `PER_SHARD` value decides which
+7 -3
View File
@@ -72,16 +72,20 @@ await puter.kv.remove('todos', id);
```
To delete several items, pass each ID as a separate argument. This clears every
completed todo:
completed todo, 50 at a time:
```js
const doneIds = items.filter((item) => item.done).map((item) => item.id);
if ( doneIds.length > 0 ) {
await puter.kv.remove('todos', ...doneIds);
for ( let i = 0; i < doneIds.length; i += 50 ) {
await puter.kv.remove('todos', ...doneIds.slice(i, i + 50));
}
```
All the IDs in one call go into one write of limited size, and a call with too
many rejects with `bad_request`. [`puter.kv.remove()`](/KV/remove/) explains
the limit.
## When to Switch
One key has a [size limit](/KV/MAX_VALUE_SIZE/) that fits a few thousand small
+9 -5
View File
@@ -63,9 +63,11 @@ IDs from
[`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)
don't contain dots, so they work without it.
An empty string, `__proto__`, `constructor` and `prototype` can't be field names,
even inside `member()`, and the call rejects with `bad_request`. If users can
type anything, add a prefix, like `member('tag:' + value)`.
The names `__proto__`, `constructor` and `prototype` can't be field names, even
inside `member()`, and the call rejects with `bad_request`. An empty string
inside `member()` is rejected the same way. Without `member()`, an empty string
is the path to the whole value, so the call replaces the whole set. If users
can type anything, add a prefix, like `member('tag:' + value)`.
## Remove a Value
@@ -76,8 +78,10 @@ await puter.kv.remove('bookmarks', member(url));
```
Removing a value that isn't in the set does nothing. To remove several at once,
pass each one as a separate argument. Passing the same value twice in one call
rejects with `bad_request`, so remove duplicates first:
pass each one as a separate argument. One call fits a limited number of values,
like [`puter.kv.update()`](/KV/update/), so split bigger removals into several
calls. Passing the same value twice in one call rejects with `bad_request`, so
remove duplicates first:
```js
await puter.kv.remove('tags', ...[ ...new Set(tagsToRemove) ].map(member));