1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-07-12 13:48:35 +02:00
unleash.unleash/src/lib/db/role-store.ts
2022-01-11 09:23:26 +01:00

89 lines
2.2 KiB
TypeScript

import EventEmitter from 'events';
import { Knex } from 'knex';
import { Logger, LogProvider } from '../logger';
import NotFoundError from '../error/notfound-error';
import { ICustomRole } from 'lib/types/model';
import { ICustomRoleInsert } from 'lib/types/stores/role-store';
const TABLE = 'roles';
const COLUMNS = ['id', 'name', 'description', 'created_at'];
interface IRoleRow {
id: number;
name: string;
description: string;
created_at: Date;
}
export default class RoleStore {
private logger: Logger;
private eventBus: EventEmitter;
private db: Knex;
constructor(db: Knex, eventBus: EventEmitter, getLogger: LogProvider) {
this.db = db;
this.eventBus = eventBus;
this.logger = getLogger('lib/db/role-store.ts');
}
async getAll(): Promise<ICustomRole[]> {
const rows = await this.db
.select(COLUMNS)
.from(TABLE)
.orderBy('name', 'asc');
return rows.map(this.mapRow);
}
async create(role: ICustomRoleInsert): Promise<ICustomRole> {
const row = await this.db(TABLE).insert(role).returning('*');
return this.mapRow(row[0]);
}
async delete(id: number): Promise<void> {
return this.db(TABLE).where({ id }).del();
}
async get(id: number): Promise<ICustomRole> {
const rows = await this.db
.select(COLUMNS)
.from(TABLE)
.where({ id })
.orderBy('name', 'asc');
return this.mapRow(rows[0]);
}
async exists(id: number): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE id = ?) AS present`,
[id],
);
const { present } = result.rows[0];
return present;
}
async deleteAll(): Promise<void> {
return this.db(TABLE).del();
}
mapRow(row: IRoleRow): ICustomRole {
if (!row) {
throw new NotFoundError('No project found');
}
return {
id: row.id,
name: row.name,
description: row.description,
createdAt: row.created_at,
};
}
destroy(): void {}
}
module.exports = RoleStore;