All files / src/lib/db setting-store.ts

100% Statements 23/23
100% Branches 3/3
90.91% Functions 10/11
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76        69x   69x           87x 87x         5x                 7x       13x       13x 13x       86x   86x 61x   25x         12x 12x 5x   7x         2x       1x           2x 5x       69x  
import { Knex } from 'knex';
import { Logger, LogProvider } from '../logger';
import { ISettingStore } from '../types/stores/settings-store';
 
const TABLE = 'settings';
 
export default class SettingStore implements ISettingStore {
    private db: Knex;
 
    private logger: Logger;
 
    constructor(db: Knex, getLogger: LogProvider) {
        this.db = db;
        this.logger = getLogger('settings-store.ts');
    }
 
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    async updateRow(name: string, content: any): Promise<void> {
        return this.db(TABLE)
            .where('name', name)
            .update({
                content: JSON.stringify(content),
            });
    }
 
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    async insertNewRow(name: string, content: any) {
        return this.db(TABLE).insert({ name, content });
    }
 
    async exists(name: string): Promise<boolean> {
        const result = await this.db.raw(
            `SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE name = ?) AS present`,
            [name],
        );
        const { present } = result.rows[0];
        return present;
    }
 
    async get(name: string): Promise<any> {
        const result = await this.db.select().from(TABLE).where('name', name);
 
        if (result.length > 0) {
            return result[0].content;
        }
        return undefined;
    }
 
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    async insert(name: string, content: any): Promise<void> {
        const exists = await this.exists(name);
        if (exists) {
            await this.updateRow(name, content);
        } else {
            await this.insertNewRow(name, content);
        }
    }
 
    async delete(name: string): Promise<void> {
        await this.db(TABLE).where({ name }).del();
    }
 
    async deleteAll(): Promise<void> {
        await this.db(TABLE).del();
    }
 
    destroy(): void {}
 
    async getAll(): Promise<any[]> {
        const rows = await this.db(TABLE).select();
        return rows.map((r) => r.content);
    }
}
 
module.exports = SettingStore;