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

57.5% Statements 23/40
0% Branches 0/3
55% Functions 11/20
56.41% Lines 22/39

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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186      69x                 69x         69x                 69x               87x 87x 87x                         6x             6x                                                                             4x 4x     4x 4x               6x       6x                                             28x               6x               85x             2x               3x             14x             61x          
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,
    ICustomRoleUpdate,
    IRoleStore,
} from 'lib/types/stores/role-store';
import { IRole, IUserRole } from 'lib/types/stores/access-store';
 
const T = {
    ROLE_USER: 'role_user',
    ROLES: 'roles',
};
 
const COLUMNS = ['id', 'name', 'description', 'type'];
 
interface IRoleRow {
    id: number;
    name: string;
    description: string;
    type: string;
}
 
export default class RoleStore implements IRoleStore {
    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(T.ROLES)
            .orderBy('name', 'asc');
 
        return rows.map(this.mapRow);
    }
 
    async create(role: ICustomRoleInsert): Promise<ICustomRole> {
        const row = await this.db(T.ROLES)
            .insert({
                name: role.name,
                description: role.description,
                type: role.roleType,
            })
            .returning('*');
        return this.mapRow(row[0]);
    }
 
    async delete(id: number): Promise<void> {
        return this.db(T.ROLES).where({ id }).del();
    }
 
    async get(id: number): Promise<ICustomRole> {
        const rows = await this.db.select(COLUMNS).from(T.ROLES).where({ id });
        Iif (rows.length === 0) {
            throw new NotFoundError(`Could not find role with id: ${id}`);
        }
        return this.mapRow(rows[0]);
    }
 
    async update(role: ICustomRoleUpdate): Promise<ICustomRole> {
        const rows = await this.db(T.ROLES)
            .where({
                id: role.id,
            })
            .update({
                id: role.id,
                name: role.name,
                description: role.description,
            })
            .returning('*');
        return this.mapRow(rows[0]);
    }
 
    async exists(id: number): Promise<boolean> {
        const result = await this.db.raw(
            `SELECT EXISTS (SELECT 1 FROM ${T.ROLES} WHERE id = ?) AS present`,
            [id],
        );
        const { present } = result.rows[0];
        return present;
    }
 
    async nameInUse(name: string, existingId?: number): Promise<boolean> {
        let query = this.db(T.ROLES).where({ name }).returning('id');
        Iif (existingId) {
            query = query.andWhereNot({ id: existingId });
        }
        const result = await query;
        return result.length > 0;
    }
 
    async deleteAll(): Promise<void> {
        return this.db(T.ROLES).del();
    }
 
    mapRow(row: IRoleRow): ICustomRole {
        Iif (!row) {
            throw new NotFoundError('No row');
        }
 
        return {
            id: row.id,
            name: row.name,
            description: row.description,
            type: row.type,
        };
    }
 
    async getRoles(): Promise<IRole[]> {
        return this.db
            .select(['id', 'name', 'type', 'description'])
            .from<IRole>(T.ROLES);
    }
 
    async getRoleWithId(id: number): Promise<IRole> {
        return this.db
            .select(['id', 'name', 'type', 'description'])
            .where('id', id)
            .first()
            .from<IRole>(T.ROLES);
    }
 
    async getProjectRoles(): Promise<IRole[]> {
        return this.db
            .select(['id', 'name', 'type', 'description'])
            .from<IRole>(T.ROLES)
            .where('type', 'custom')
            .orWhere('type', 'project');
    }
 
    async getRolesForProject(projectId: string): Promise<IRole[]> {
        return this.db
            .select(['r.id', 'r.name', 'r.type', 'ru.project', 'r.description'])
            .from<IRole>(`${T.ROLE_USER} as ru`)
            .innerJoin(`${T.ROLES} as r`, 'ru.role_id', 'r.id')
            .where('project', projectId);
    }
 
    async getRootRoles(): Promise<IRole[]> {
        return this.db
            .select(['id', 'name', 'type', 'description'])
            .from<IRole>(T.ROLES)
            .where('type', 'root');
    }
 
    async removeRolesForProject(projectId: string): Promise<void> {
        return this.db(T.ROLE_USER)
            .where({
                project: projectId,
            })
            .delete();
    }
 
    async getRootRoleForAllUsers(): Promise<IUserRole[]> {
        const rows = await this.db
            .select('id', 'user_id')
            .distinctOn('user_id')
            .from(`${T.ROLES} AS r`)
            .leftJoin(`${T.ROLE_USER} AS ru`, 'r.id', 'ru.role_id')
            .where('r.type', '=', 'root');
 
        return rows.map((row) => ({
            roleId: Number(row.id),
            userId: Number(row.user_id),
        }));
    }
 
    async getRoleByName(name: string): Promise<IRole> {
        return this.db(T.ROLES).where({ name }).first();
    }
 
    destroy(): void {}
}