grill-blog/mockdb.ts

76 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-05-13 22:50:54 +01:00
// deno-lint-ignore-file require-await
import { Database, Session, User } from "./database.ts";
import { Err, None, Ok, Option, Result, Some } from "./utils.ts";
export class MockDb implements Database {
public inErronousState = false;
public users: User[] = [];
public sessions: Session[] = [];
public async createUser(
init: Omit<User, "id">,
): Promise<Result<User, string>> {
if (this.inErronousState) return Err("error");
const user: User = {
...init,
id: this.users.length,
};
this.users.push(user);
return Ok(user);
}
public async userWithId(
id: number,
): Promise<Result<Option<User>, string>> {
if (this.inErronousState) return Err("error");
const found = this.users.find((user) => user.id === id);
if (found === undefined) {
return Ok(None);
}
return Ok(Some(found));
}
public async userWithUsername(
username: string,
): Promise<Result<Option<User>, string>> {
if (this.inErronousState) return Err("error");
const found = this.users.find((user) => user.username === username);
if (found === undefined) {
return Ok(None);
}
return Ok(Some(found));
}
public async userWithUsernameExists(
username: string,
): Promise<Result<boolean, string>> {
if (this.inErronousState) return Err("error");
return Ok(
this.users.find((user) => user.username === username) !== undefined,
);
}
public async createSession(
init: Omit<Session, "id">,
): Promise<Result<Session, string>> {
if (this.inErronousState) return Err("error");
const session: Session = {
...init,
id: this.users.length,
};
this.sessions.push(session);
return Ok(session);
}
public async sessionWithId(
id: number,
): Promise<Result<Option<Session>, string>> {
if (this.inErronousState) return Err("error");
const found = this.sessions.find((session) => session.id === id);
if (found === undefined) {
return Ok(None);
}
return Ok(Some(found));
}
}