100 lines
2.2 KiB
TypeScript
100 lines
2.2 KiB
TypeScript
import {
|
|
APIErrorCode,
|
|
APIException,
|
|
type CreateDumpRequest,
|
|
type Dump,
|
|
type UpdateDumpRequest,
|
|
} from "../model/interfaces.ts";
|
|
import { db, dumpApiToRow, dumpRowToApi, isDumpRow } from "../model/db.ts";
|
|
|
|
export function createDump(
|
|
request: CreateDumpRequest,
|
|
userId: string,
|
|
): Dump {
|
|
const dumpId = crypto.randomUUID();
|
|
const createdAt = new Date();
|
|
|
|
db.prepare(
|
|
`INSERT INTO dumps (id, title, description, user_id, created_at)
|
|
VALUES (?, ?, ?, ?, ?);`,
|
|
).run(
|
|
dumpId,
|
|
request.title,
|
|
request.description ?? null,
|
|
userId,
|
|
createdAt.toISOString(),
|
|
);
|
|
|
|
return {
|
|
id: dumpId,
|
|
title: request.title,
|
|
description: request.description ?? undefined,
|
|
userId: userId,
|
|
createdAt,
|
|
};
|
|
}
|
|
|
|
export function getDump(dumpId: string): Dump {
|
|
const dumpRow = db.prepare(
|
|
`SELECT id, title, description, user_id, created_at
|
|
FROM dumps WHERE id = ?;`,
|
|
).get(dumpId);
|
|
|
|
if (!dumpRow || !isDumpRow(dumpRow)) {
|
|
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
|
|
}
|
|
|
|
return dumpRowToApi(dumpRow);
|
|
}
|
|
|
|
export function listDumps(): Dump[] {
|
|
const dumpRows = db.prepare(
|
|
`SELECT id, title, description, user_id, created_at FROM dumps;`,
|
|
).all();
|
|
|
|
if (!dumpRows || !dumpRows.every(isDumpRow)) {
|
|
throw new APIException(APIErrorCode.NOT_FOUND, 404, "No dump found");
|
|
}
|
|
|
|
const dumps: Dump[] = dumpRows.map(dumpRowToApi);
|
|
|
|
return dumps;
|
|
}
|
|
|
|
export function updateDump(
|
|
dumpId: string,
|
|
request: UpdateDumpRequest,
|
|
): Dump {
|
|
const dump = getDump(dumpId);
|
|
|
|
const updatedDump = {
|
|
...dump,
|
|
...request,
|
|
};
|
|
const updatedDumpRow = dumpApiToRow(updatedDump);
|
|
|
|
const dumpResult = db.prepare(
|
|
`UPDATE dumps SET title = ?, description = ? WHERE id = ?;`,
|
|
).run(
|
|
updatedDumpRow.title,
|
|
updatedDumpRow.description,
|
|
updatedDumpRow.id,
|
|
);
|
|
|
|
if (dumpResult.changes === 0) {
|
|
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
|
|
}
|
|
|
|
return updatedDump;
|
|
}
|
|
|
|
export function deleteDump(dumpId: string): void {
|
|
const result = db.prepare(
|
|
`DELETE FROM dumps WHERE id = ?;`,
|
|
).run(dumpId);
|
|
|
|
if (result.changes === 0) {
|
|
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
|
|
}
|
|
}
|