-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayground.ts
59 lines (53 loc) · 1.43 KB
/
playground.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
import { NextRequest, NextResponse } from "next/server";
import { ActionClient, ActionClientError } from "./dist/index";
import { z } from "zod";
type User = {
id: string;
};
type ActionContextType = { user?: User };
const client = ({ req }: { req: NextRequest }) => {
return new ActionClient<ActionContextType>({
req,
ctx: { user: undefined },
});
};
const authenticatedClient = ({ req }: { req: NextRequest }) => {
return new ActionClient<Required<ActionContextType>>({
req,
}).use(async () => {
const user = JSON.parse(req.cookies.get("AUTH")?.value ?? "{}") as
| {
id: string;
}
| undefined;
if (!user?.id) {
throw new ActionClientError("Failed to parse", 401);
}
return { ctx: { user } };
});
};
export const GET = (req: NextRequest) =>
client({ req })
.method("GET")
.query(
z.object({
page: z.coerce.number().default(0),
pageSize: z.coerce.number().default(25),
}),
)
.action(({ ctx, parsedQuery }) => {
console.log(ctx.user, parsedQuery);
return NextResponse.json({ success: true });
});
export const POST = (req: NextRequest) =>
authenticatedClient({ req })
.method("POST")
.json(
z.object({
title: z.string(),
}),
)
.action(({ ctx, parsedQuery, parsedInput }) => {
console.log(ctx, parsedQuery, parsedInput);
return NextResponse.json({ success: true });
});