|
1 | 1 | import { Handlers } from "$fresh/server.ts"; |
2 | 2 | import { db, initDB } from "@/lib/surreal.ts"; |
| 3 | +import { RecordId } from "@surrealdb/surrealdb"; |
| 4 | +import { ulid } from "@std/ulid"; |
| 5 | +import { hash } from "@felix/bcrypt"; |
| 6 | +import { PublicUser, PublicUserSchema } from "@/types.ts"; |
| 7 | + |
| 8 | +await initDB(); |
3 | 9 |
|
4 | 10 | export const handler: Handlers<null> = { |
5 | 11 | async GET(_req, _ctx) { |
6 | | - await initDB(); |
| 12 | + const results: PublicUser[][] = await db.query(` |
| 13 | + SELECT id, name FROM user; |
| 14 | + `); |
| 15 | + return new Response(JSON.stringify(results[0], null, 2), { |
| 16 | + headers: { "Content-Type": "application/json" }, |
| 17 | + }); |
| 18 | + }, |
7 | 19 |
|
8 | | - const users = await db.select("user"); |
| 20 | + async POST(req, _ctx) { |
| 21 | + const body = await req.json(); |
| 22 | + const { email, password } = body; |
9 | 23 |
|
10 | | - return new Response(JSON.stringify(users, null, 2), { |
11 | | - headers: { "Content-Type": "application/json" }, |
| 24 | + if (!email || !password) { |
| 25 | + return new Response( |
| 26 | + JSON.stringify({ error: "Email and password are required." }), |
| 27 | + { status: 400, headers: { "Content-Type": "application/json" } }, |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + const hashedPassword = await hash(password); |
| 32 | + const emailVerificationToken = ulid(); |
| 33 | + |
| 34 | + const user = await db.create<PublicUser>(new RecordId("user", ulid()), { |
| 35 | + email, |
| 36 | + password_hash: hashedPassword, |
| 37 | + email_verification_token: emailVerificationToken, |
12 | 38 | }); |
| 39 | + const parsed = PublicUserSchema.parse(user); |
| 40 | + |
| 41 | + return new Response( |
| 42 | + JSON.stringify(parsed, null, 2), |
| 43 | + { |
| 44 | + headers: { "Content-Type": "application/json" }, |
| 45 | + status: 201, |
| 46 | + }, |
| 47 | + ); |
13 | 48 | }, |
14 | 49 | }; |
0 commit comments