@rbac/rbac
Version:
Blazing Fast, Zero dependency, Hierarchical Role-Based Access Control for Node.js
58 lines (57 loc) • 2.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostgresRoleAdapter = void 0;
let PG;
function loadPG() {
if (!PG) {
try {
PG = require('pg');
}
catch (err) {
throw new Error('Please install "pg" to use PostgresRoleAdapter');
}
}
return PG;
}
class PostgresRoleAdapter {
constructor(options) {
this.options = options;
this.connected = false;
this.defaultTenant = 'default';
const { Client } = loadPG();
this.options.columns = {
name: 'name',
role: 'role',
tenantId: 'tenant_id',
...this.options.columns
};
this.client = new Client(options);
}
async getClient() {
if (!this.connected) {
await this.client.connect();
this.connected = true;
}
return this.client;
}
async getRoles(tenantId) {
const client = await this.getClient();
const cols = this.options.columns;
const res = await client.query(`SELECT ${cols.name}, ${cols.role} FROM ${this.options.table} WHERE ${cols.tenantId} = $1`, [tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant]);
return res.rows.reduce((acc, row) => {
acc[row[cols.name]] = JSON.parse(row[cols.role]);
return acc;
}, {});
}
async addRole(roleName, role, tenantId) {
const client = await this.getClient();
const cols = this.options.columns;
await client.query(`INSERT INTO ${this.options.table}(${cols.name}, ${cols.role}, ${cols.tenantId}) VALUES ($1, $2, $3)`, [roleName, JSON.stringify(role), tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant]);
}
async updateRoles(roles, tenantId) {
const client = await this.getClient();
const cols = this.options.columns;
await Promise.all(Object.entries(roles).map(([name, role]) => client.query(`INSERT INTO ${this.options.table}(${cols.name}, ${cols.role}, ${cols.tenantId}) VALUES ($1, $2, $3) ON CONFLICT (${cols.name}, ${cols.tenantId}) DO UPDATE SET ${cols.role} = EXCLUDED.${cols.role}`, [name, JSON.stringify(role), tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant])));
}
}
exports.PostgresRoleAdapter = PostgresRoleAdapter;