Add a real db
This commit is contained in:
@@ -1,66 +1,17 @@
|
||||
import { monotonicUlid } from "@std/ulid";
|
||||
import { Database } from "@paulaboks/boksy";
|
||||
|
||||
import { DATABASE_PATH } from "@/src/server_constants.ts";
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
export interface User extends Record<string, unknown> {
|
||||
name: string;
|
||||
code: string;
|
||||
admin: boolean;
|
||||
}
|
||||
|
||||
interface Database {
|
||||
users: Record<string, User>;
|
||||
}
|
||||
type Schema = {
|
||||
users: User;
|
||||
};
|
||||
|
||||
let write_queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
function get_database_path() {
|
||||
if (!DATABASE_PATH) {
|
||||
throw new Error("DATABASE_PATH is not set");
|
||||
}
|
||||
return DATABASE_PATH;
|
||||
}
|
||||
|
||||
async function read_database(): Promise<Database> {
|
||||
try {
|
||||
return JSON.parse(await Deno.readTextFile(get_database_path()));
|
||||
} catch (error) {
|
||||
if (error instanceof Deno.errors.NotFound) return { users: {} };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Writes to a temp file first so a crash mid-write can't corrupt the database
|
||||
async function write_database(database: Database) {
|
||||
const path = get_database_path();
|
||||
await Deno.writeTextFile(`${path}.tmp`, JSON.stringify(database, null, "\t"));
|
||||
await Deno.rename(`${path}.tmp`, path);
|
||||
}
|
||||
|
||||
// Runs read-modify-write operations one at a time so concurrent calls don't overwrite each other
|
||||
function with_write_lock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const result = write_queue.then(fn);
|
||||
write_queue = result.catch(() => {});
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function get_user(id: string): Promise<User | undefined> {
|
||||
const database = await read_database();
|
||||
return database.users[id];
|
||||
}
|
||||
|
||||
export function new_user(user: Omit<User, "id">): Promise<User> {
|
||||
return with_write_lock(async () => {
|
||||
const database = await read_database();
|
||||
const created: User = { ...user, id: monotonicUlid() };
|
||||
database.users[created.id] = created;
|
||||
await write_database(database);
|
||||
return created;
|
||||
});
|
||||
}
|
||||
|
||||
export async function get_all_users(): Promise<User[]> {
|
||||
const database = await read_database();
|
||||
return Object.values(database.users);
|
||||
}
|
||||
export const db = await Database.open<Schema>(DATABASE_PATH ?? ":memory:", {
|
||||
users: ["code"],
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user