Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active September 28, 2023 00:29
Show Gist options
  • Save mmyoji/e93bc82416b661eb3f604f75cf8ee188 to your computer and use it in GitHub Desktop.
Save mmyoji/e93bc82416b661eb3f604f75cf8ee188 to your computer and use it in GitHub Desktop.
Code examples of Deno Queues
// https://deno.com/blog/queues
function listenQueue<T>(fn: (msg: T) => Promise<void>) {
//
}
// lib/kv/queue/_core.ts
const messageTypes = {
foo: "foo",
bar: "bar",
} as const;
type MessageType = (typeof messageTypes)[keyof typeof messageTypes];
type Message = {
type: MessageType;
payload?: unknown;
};
type HandlerFunc = (msg: Message) => void | Promise<void>;
type Handler = {
type: MessageType;
run: HandlerFunc;
};
// lib/kv/queue/foo.handler.ts
const fooHandler: Handler = {
type: messageTypes.foo,
run: async (msg) => {
// asserts payload is XXX;
console.log("foo", msg);
}};
// lib/kv/queue/bar.handler.ts
const barHandler: Handler = {
type: messageTypes.bar,
run: async (msg) => {
// asserts payload is XXX;
console.log("bar", msg);
},
};
// lib/kv/queue/mod.ts
const handlers = new Map<MessageType, Handler>();
handlers.set(fooHandler.type, fooHandler);
handlers.set(fooHandler.type, barHandler);
// main.ts
listenQueue<Message>(async (msg) => {
const h = handlers.get(msg.type);
if (!h) {
console.error(`Unknown message: msg.type=${msg.type}`, msg);
return;
}
await h.run(msg);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment