yippee C and R from db works well

This commit is contained in:
2026-01-12 18:16:32 +13:00
parent 8794bd6aea
commit ea173dcc52
9 changed files with 57 additions and 183 deletions

View File

@@ -1,6 +1,6 @@
import { integer, pgTable, varchar, date, json } from "drizzle-orm/pg-core";
export const usersTable = pgTable("users", {
export const entryTable = pgTable("entries", {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
data: date().defaultNow(),
location: json(),

View File

@@ -1,7 +1,8 @@
import { db, Entry } from "astro:db";
import { db } from "../../../utils/db"
import { entryTable } from "../../../db/schema"
export async function GET() {
const entries = await db.select().from(Entry)
const entries = await db.select().from(entryTable)
return new Response(JSON.stringify(entries))
}

View File

@@ -1,4 +1,6 @@
import { db, Entry } from "astro:db";
import { db } from "../../../utils/db"
import { entryTable } from "../../../db/schema"
import { httpResponse } from "../../../utils/response";
export async function POST({ request }) {
@@ -6,18 +8,15 @@ export async function POST({ request }) {
try {
const body = await request.json();
await db.insert(Entry).values(body)
const entry: typeof entryTable.$inferInsert = body
await db.insert(entryTable).values(entry)
} catch(e) {
return new Response(
JSON.stringify({
"error": `Malformed JSON (${e})`
}),{ status: 400 }
)
return httpResponse({ "error": `Malformed JSON (${e})` }, 400)
}
return new Response(null, { status: 200 });
return httpResponse(null, 200);
}
return new Response(null, { status: 400 });
return httpResponse(null, 400);
}

View File

@@ -1,4 +1,4 @@
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';
const db = drizzle(process.env.DATABASE_URL!);
export const db = drizzle(process.env.DATABASE_URL!);

5
src/utils/response.ts Normal file
View File

@@ -0,0 +1,5 @@
export function httpResponse(data: object | null, code: number) {
return new Response(JSON.stringify(data), {
status: code
})
}