-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
post.ts
151 lines (138 loc) Β· 3.84 KB
/
post.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/**
*
* This is an example router, you can delete this file and then update `../pages/api/trpc/[trpc].tsx`
*/
import type { Post } from '@prisma/client';
import { observable } from '@trpc/server/observable';
import { EventEmitter } from 'events';
import { prisma } from '../prisma';
import { z } from 'zod';
import { authedProcedure, publicProcedure, router } from '../trpc';
interface MyEvents {
add: (data: Post) => void;
isTypingUpdate: () => void;
}
declare interface MyEventEmitter {
on<TEv extends keyof MyEvents>(event: TEv, listener: MyEvents[TEv]): this;
off<TEv extends keyof MyEvents>(event: TEv, listener: MyEvents[TEv]): this;
once<TEv extends keyof MyEvents>(event: TEv, listener: MyEvents[TEv]): this;
emit<TEv extends keyof MyEvents>(
event: TEv,
...args: Parameters<MyEvents[TEv]>
): boolean;
}
class MyEventEmitter extends EventEmitter {}
// In a real app, you'd probably use Redis or something
const ee = new MyEventEmitter();
// who is currently typing, key is `name`
const currentlyTyping: Record<string, { lastTyped: Date }> =
Object.create(null);
// every 1s, clear old "isTyping"
const interval = setInterval(() => {
let updated = false;
const now = Date.now();
for (const [key, value] of Object.entries(currentlyTyping)) {
if (now - value.lastTyped.getTime() > 3e3) {
delete currentlyTyping[key];
updated = true;
}
}
if (updated) {
ee.emit('isTypingUpdate');
}
}, 3e3);
process.on('SIGTERM', () => {
clearInterval(interval);
});
export const postRouter = router({
add: authedProcedure
.input(
z.object({
id: z.string().uuid().optional(),
text: z.string().min(1),
}),
)
.mutation(async ({ input, ctx }) => {
const { name } = ctx.user;
const post = await prisma.post.create({
data: {
...input,
name,
source: 'GITHUB',
},
});
ee.emit('add', post);
delete currentlyTyping[name];
ee.emit('isTypingUpdate');
return post;
}),
isTyping: authedProcedure
.input(z.object({ typing: z.boolean() }))
.mutation(({ input, ctx }) => {
const { name } = ctx.user;
if (!input.typing) {
delete currentlyTyping[name];
} else {
currentlyTyping[name] = {
lastTyped: new Date(),
};
}
ee.emit('isTypingUpdate');
}),
infinite: publicProcedure
.input(
z.object({
cursor: z.date().nullish(),
take: z.number().min(1).max(50).nullish(),
}),
)
.query(async ({ input }) => {
const take = input.take ?? 10;
const cursor = input.cursor;
const page = await prisma.post.findMany({
orderBy: {
createdAt: 'desc',
},
cursor: cursor ? { createdAt: cursor } : undefined,
take: take + 1,
skip: 0,
});
const items = page.reverse();
let nextCursor: typeof cursor | null = null;
if (items.length > take) {
const prev = items.shift();
nextCursor = prev!.createdAt;
}
return {
items,
nextCursor,
};
}),
onAdd: publicProcedure.subscription(() => {
return observable<Post>((emit) => {
const onAdd = (data: Post) => {
emit.next(data);
};
ee.on('add', onAdd);
return () => {
ee.off('add', onAdd);
};
});
}),
whoIsTyping: publicProcedure.subscription(() => {
let prev: string[] | null = null;
return observable<string[]>((emit) => {
const onIsTypingUpdate = () => {
const newData = Object.keys(currentlyTyping);
if (!prev || prev.toString() !== newData.toString()) {
emit.next(newData);
}
prev = newData;
};
ee.on('isTypingUpdate', onIsTypingUpdate);
return () => {
ee.off('isTypingUpdate', onIsTypingUpdate);
};
});
}),
});