-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathqueues.ts
48 lines (41 loc) · 1.58 KB
/
queues.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* @title Deno queues
* @difficulty intermediate
* @tags cli, deploy
* @run --unstable-kv <url>
* @resource {https://docs.deno.com/deploy/kv/manual/queue_overview} Deno Queues user guide
* @resource {https://docs.deno.com/api/deno/~/Deno.Kv} Deno Queues Runtime API docs
* @group Unstable APIs
*
* <strong>Warning: This is an unstable API that is subject to change or removal at anytime.</strong><br>Deno Queues, built on Deno KV, allow you to offload parts of your application
* or schedule work for the future to run asynchronously. It's an easy way to add
* scalable background processing to your project.
*/
// Describe the shape of your message object (optional)
interface Notification {
forUser: string;
body: string;
}
// Get a reference to a KV instance
const kv = await Deno.openKv();
// Create a notification object
const message: Notification = {
forUser: "alovelace",
body: "You've got mail!",
};
// Enqueue the message for immediate delivery
await kv.enqueue(message);
// Enqueue the message for delivery in 3 days
const delay = 1000 * 60 * 60 * 24 * 3;
await kv.enqueue(message, { delay });
// Retrieve an unsent message by configuring a key
const backupKey = ["failed_notifications", "alovelace", Date.now()];
await kv.enqueue(message, { keysIfUndelivered: [backupKey] });
// ... disaster strikes ...
// Get the unsent message
const r = await kv.get<Notification>(backupKey);
console.log("Found failed notification for:", r.value?.forUser);
// Listen for and handle messages.
kv.listenQueue((msg: Notification) => {
console.log(`Dear ${msg.forUser}: ${msg.body}`);
});