-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdb-listener.ts
32 lines (28 loc) · 951 Bytes
/
db-listener.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
import {z} from "zod";
import {camelCaseKeys, Comment, Post, RecordVersion} from "./schema.ts";
import {postgresClient} from "./db.ts";
export const ChannelMap = {
new_posts: z.preprocess(camelCaseKeys, Post),
new_comments: z.preprocess(camelCaseKeys, Comment),
audit_changes: z.preprocess(camelCaseKeys, RecordVersion),
};
export type ChannelMap = typeof ChannelMap;
type ListenerConfig<Channel extends keyof ChannelMap> = {
channel: Channel;
onNotify: (payload: z.infer<ChannelMap[Channel]>) => void;
onListen: () => void;
};
export const getDBListener = <Channel extends keyof ChannelMap>(
props: ListenerConfig<Channel>,
) => {
return postgresClient.listen(
props.channel,
(payloadString) => {
const payload = ChannelMap[props.channel].parse(
JSON.parse(payloadString),
);
props.onNotify(payload);
},
props.onListen,
);
};