From 76635326ecb778e8540c4e0e3d400acfd9a46216 Mon Sep 17 00:00:00 2001 From: Tau Date: Mon, 29 Apr 2019 10:25:05 -0400 Subject: [PATCH] idz: Add SqlBackgroundsRepository --- src/idz/db/backgrounds.ts | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/idz/db/backgrounds.ts diff --git a/src/idz/db/backgrounds.ts b/src/idz/db/backgrounds.ts new file mode 100644 index 0000000..9f055d0 --- /dev/null +++ b/src/idz/db/backgrounds.ts @@ -0,0 +1,55 @@ +import { Client } from "pg"; +import * as sql from "sql-bricks"; + +import { _findProfile } from "./_util"; +import { BackgroundCode, ExtId } from "../model/base"; +import { Profile } from "../model/profile"; +import { FlagRepository } from "../repo"; +import { generateId } from "../../db"; + +export class SqlBackgroundsRepository + implements FlagRepository { + constructor(private readonly _conn: Client) {} + + async loadAll(extId: ExtId): Promise> { + const loadSql = sql + .select("bg.background_no") + .from("idz.background_unlock bg") + .join("idz.profile p", { "bg.profile_id": "p.id" }) + .where("p.ext_id", extId) + .toParams(); + + const { rows } = await this._conn.query(loadSql); + const result = new Set(); + + for (const row of rows) { + result.add(row.background_no); + } + + return result; + } + + async saveAll( + extId: ExtId, + flags: Set + ): Promise { + const profileId = await _findProfile(this._conn, extId); + const existing = await this.loadAll(extId); + + for (const flag of flags) { + if (existing.has(flag)) { + continue; + } + + const saveSql = sql + .insert("idz.background_unlock", { + id: generateId(), + profile_id: profileId, + background_no: flag, + }) + .toParams(); + + await this._conn.query(saveSql); + } + } +}