-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathpost.ts
104 lines (98 loc) Β· 2.62 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
/**
*
* This is an example router, you can delete this file and then update `../pages/api/trpc/[trpc].tsx`
*/
import { router, publicProcedure } from '../trpc';
import type { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { prisma } from '~/server/prisma';
/**
* Default selector for Post.
* It's important to always explicitly say which fields you want to return in order to not leak extra information
* @see https://github.com/prisma/prisma/issues/9353
*/
const defaultPostSelect = {
id: true,
title: true,
text: true,
createdAt: true,
updatedAt: true,
} satisfies Prisma.PostSelect;
export const postRouter = router({
list: publicProcedure
.input(
z.object({
limit: z.number().min(1).max(100).nullish(),
cursor: z.string().nullish(),
}),
)
.query(async ({ input }) => {
/**
* For pagination docs you can have a look here
* @see https://trpc.io/docs/v11/useInfiniteQuery
* @see https://www.prisma.io/docs/concepts/components/prisma-client/pagination
*/
const limit = input.limit ?? 50;
const { cursor } = input;
const items = await prisma.post.findMany({
select: defaultPostSelect,
// get an extra item at the end which we'll use as next cursor
take: limit + 1,
where: {},
cursor: cursor
? {
id: cursor,
}
: undefined,
orderBy: {
createdAt: 'desc',
},
});
let nextCursor: typeof cursor | undefined = undefined;
if (items.length > limit) {
// Remove the last item and use it as next cursor
const nextItem = items.pop()!;
nextCursor = nextItem.id;
}
return {
items: items.reverse(),
nextCursor,
};
}),
byId: publicProcedure
.input(
z.object({
id: z.string(),
}),
)
.query(async ({ input }) => {
const { id } = input;
const post = await prisma.post.findUnique({
where: { id },
select: defaultPostSelect,
});
if (!post) {
throw new TRPCError({
code: 'NOT_FOUND',
message: `No post with id '${id}'`,
});
}
return post;
}),
add: publicProcedure
.input(
z.object({
id: z.string().uuid().optional(),
title: z.string().min(1).max(32),
text: z.string().min(1),
}),
)
.mutation(async ({ input }) => {
const post = await prisma.post.create({
data: input,
select: defaultPostSelect,
});
return post;
}),
});