-
-
Notifications
You must be signed in to change notification settings - Fork 722
/
Copy pathindex.ts
56 lines (45 loc) · 1.56 KB
/
index.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
import { Client } from '@neondatabase/serverless';
import { eq } from 'drizzle-orm/expressions';
import type { NeonDatabase } from 'drizzle-orm/neon-serverless';
import { drizzle } from 'drizzle-orm/neon-serverless';
import type { Request as IttyRequest, Route } from 'itty-router';
import { Router } from 'itty-router';
import { json } from 'itty-router-extras';
import { users } from './schema';
interface Env {
DATABASE_URL: string;
}
interface Request extends IttyRequest {
client: Client;
db: NeonDatabase;
}
interface Methods {
get: Route;
post: Route;
}
async function injectDB(request: Request, env: Env) {
request.client = new Client(env.DATABASE_URL);
request.db = drizzle(request.client);
}
const router = Router<Request, Methods>({ base: '/' });
router.get('/health', async (req: Request, env: Env, ctx: ExecutionContext) => {
return json({ status: 'ok' });
});
router.get('/users', injectDB, async (req: Request, env: Env, ctx: ExecutionContext) => {
req.client.connect();
const result = await req.db.select().from(users);
ctx.waitUntil(req.client.end());
return json({ status: 'ok', result });
});
router.get('/users/:id', injectDB, async (req: Request, env: Env) => {
const result = await req.db.select().from(users).where(eq(users.id, req.params!['id'])).execute();
return json(result);
});
router.post('/users', injectDB, async (req: Request, env: Env) => {
const { name, email } = await req.json!();
const res = await req.db.insert(users).values({ name, email }).returning().execute();
return json({ res });
});
export default {
fetch: router.handle,
};