-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-v2.ts
More file actions
62 lines (59 loc) · 2.14 KB
/
Copy pathbasic-v2.ts
File metadata and controls
62 lines (59 loc) · 2.14 KB
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
import { SupabaseContext, withSupabase } from "@supabase/server";
import { applyMiddlewareWithSupabaseContext } from "../src/v2/middleware-with-supabase-context.ts";
import { httpMethodWithSupabaseContextMiddlewareFn } from "../src/v2/http-method-with-supabase-context-middleware.ts";
import z from "zod";
import {
ZodValidateBodyWithSupabaseContextMiddlewareContext,
zodValidateBodyWithSupabaseContextMiddlewareFn,
} from "../src/v2/zod-validate-body-with-supabase-context-middleware.ts";
const bodySchema = z.object({
name: z.string(),
age: z.number(),
});
export default {
fetch: withSupabase(
{
auth: ["user"],
},
applyMiddlewareWithSupabaseContext({
middlewares: [
httpMethodWithSupabaseContextMiddlewareFn("POST"),
zodValidateBodyWithSupabaseContextMiddlewareFn(bodySchema),
// zodValidationProcessingWithSupabaseContextMiddlewareFn(bodySchema),
],
// deno-lint-ignore require-await
handler: async <T extends SupabaseContext<unknown>>(_req: Request, ctx: T) => {
// ZodValidateBodyWithSupabaseContextMiddlewareContext is injected by middleware function - zodValidateBodyWithSupabaseContextMiddlewareFn(...)
const {
success,
data,
error,
} = (ctx as unknown as ZodValidateBodyWithSupabaseContextMiddlewareContext<
z.infer<typeof bodySchema>
>).validation;
if (success) { // pass validation
const name = data?.name ?? "";
const age = data?.age ?? 0;
return new Response(
JSON.stringify({ success: true, message: `Hello ${name}, you are ${age} years old` }),
{
headers: {
"Content-Type": "application/json",
},
},
);
} else {
const msg = error?.issues.map((issue) => issue.message).join(", ") ?? `unknown error`;
return new Response(
JSON.stringify({ success: false, message: `error: ${msg}` }),
{
headers: {
"Content-Type": "application/json",
},
},
);
}
},
}),
),
};