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(data: unknown): Promise { 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(query: TemplateStringsArray | Prisma.Sql, ...values: any[]): Promise { const data = await this.$queryRaw(query, ...values); return this.queryUniqueOrThrow(data); } async $queryRawUnsafeUnique(query: string, ...values: any[]): Promise { const data = await this.$queryRawUnsafe(query, ...values); return this.queryUniqueOrThrow(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!"); } }