73 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-04-16 19:06:23 -04:00
import type { DrizzleD1Database } from "drizzle-orm/d1";
2024-04-16 18:19:34 -04:00
import { drizzle } from "drizzle-orm/d1";
2024-04-16 19:06:23 -04:00
import { json } from "itty-router-extras";
import { ZodError, z } from "zod";
import { user, sandbox } from "./schema";
import * as schema from "./schema";
2024-04-22 00:30:50 -04:00
import { eq } from "drizzle-orm";
const success = new Response("Success", { status: 200 });
const notFound = new Response("Not Found", { status: 404 });
const methodNotAllowed = new Response("Method Not Allowed", { status: 405 });
2024-04-16 18:19:34 -04:00
export interface Env {
DB: D1Database;
2024-04-22 00:30:50 -04:00
R2: R2Bucket;
2024-04-16 18:19:34 -04:00
}
2024-04-21 22:55:49 -04:00
// https://github.com/drizzle-team/drizzle-orm/tree/main/examples/cloudflare-d1
2024-04-16 18:19:34 -04:00
export default {
2024-04-17 21:24:57 -04:00
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname;
const method = request.method;
const db = drizzle(env.DB, { schema });
2024-04-17 21:24:57 -04:00
2024-04-22 00:30:50 -04:00
// ^\/api\/sandbox\/([^\/]+)\/((init|files))$
if (new RegExp("^/api/sandbox/([^/]+)/((init|files))$").test(path)) {
const sandboxId = path.split("/")[2];
const command = path.split("/")[3] as "init" | "files";
if (command === "init") {
await db.update(sandbox).set({ init: true }).where(eq(sandbox.id, sandboxId));
}
} else if (path === "/api/user") {
2024-04-18 15:25:20 -04:00
if (method === "GET") {
const params = url.searchParams;
2024-04-18 15:25:20 -04:00
if (params.has("id")) {
2024-04-17 22:55:02 -04:00
const id = params.get("id") as string;
const res = await db.query.user.findFirst({
where: (user, { eq }) => eq(user.id, id),
with: {
sandbox: true,
},
});
2024-04-17 22:55:02 -04:00
return json(res ?? {});
} else {
2024-04-18 15:25:20 -04:00
const res = await db.select().from(user).all();
return json(res ?? {});
2024-04-17 22:55:02 -04:00
}
2024-04-18 15:25:20 -04:00
} else if (method === "POST") {
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
});
const body = await request.json();
const { id, name, email } = userSchema.parse(body);
const res = await db.insert(user).values({ id, name, email }).returning().get();
return json({ res });
2024-04-17 21:24:57 -04:00
} else {
2024-04-22 00:30:50 -04:00
return methodNotAllowed;
2024-04-17 21:24:57 -04:00
}
2024-04-22 00:30:50 -04:00
} else return notFound;
2024-04-17 21:24:57 -04:00
},
2024-04-16 18:19:34 -04:00
};