54 lines
2.3 KiB
TypeScript
54 lines
2.3 KiB
TypeScript
import { Prisma, PrismaClient } from "@prisma/client";
|
|
import { VixpressService } from "@dunemask/vix";
|
|
import { VERB } from "@dunemask/vix/logging";
|
|
import UsersTableService from "./tables/UsersTableService.js";
|
|
import RolePolicyTableService from "./tables/RolePolicyTableService.js";
|
|
import ProjectTableService from "./tables/ProjectTableService.js";
|
|
import KeyPairTableService from "./tables/KeyPairTableService.js";
|
|
|
|
export class DBPrismaClient extends PrismaClient {
|
|
private async queryUniqueOrThrow<T = unknown>(data: unknown): Promise<T | undefined> {
|
|
if (!Array.isArray(data)) throw Error("Returned non-array!");
|
|
if (data.length > 1) throw Error("Non unique value found!");
|
|
return data.length === 1 ? data[0] : undefined;
|
|
}
|
|
async $queryRawUnique<T = unknown>(query: TemplateStringsArray | Prisma.Sql, ...values: any[]): Promise<T | undefined> {
|
|
const data = await this.$queryRaw(query, ...values);
|
|
return this.queryUniqueOrThrow<T>(data);
|
|
}
|
|
|
|
async $queryRawUnsafeUnique<T = unknown>(query: string, ...values: any[]): Promise<T | undefined> {
|
|
const data = await this.$queryRawUnsafe(query, ...values);
|
|
return this.queryUniqueOrThrow<T>(data);
|
|
}
|
|
}
|
|
|
|
export default class PostgresService extends VixpressService {
|
|
declare pg: DBPrismaClient;
|
|
declare users: UsersTableService;
|
|
declare rolePolicy: RolePolicyTableService;
|
|
declare project: ProjectTableService;
|
|
declare keypair: KeyPairTableService;
|
|
|
|
async configureService() {
|
|
this.pg = new DBPrismaClient({
|
|
errorFormat: "pretty",
|
|
log: ["warn", "error", "info", { emit: "event", level: "query" }],
|
|
});
|
|
this.users = new UsersTableService(this.pg);
|
|
this.rolePolicy = new RolePolicyTableService(this.pg);
|
|
this.project = new ProjectTableService(this.pg);
|
|
this.keypair = new KeyPairTableService(this.pg);
|
|
}
|
|
|
|
async startService() {
|
|
VERB("POSTGRES", "Connecting to postgres....");
|
|
await this.pg.$connect();
|
|
await this.project.$upsertDefaultProject();
|
|
await this.keypair.$upsertDefaultKeyPairs();
|
|
await this.rolePolicy.$upsertDefaultAuthorities();
|
|
const user = await this.users.$upsertDefaultRootUser();
|
|
if (!!user) VERB("APP INIT", `Created identity 'root' with password '${user.password}'!`);
|
|
if (!!user) VERB("APP INIT", "This will not be shown again!");
|
|
}
|
|
}
|