Add feature to insert default role and permission in the DB

This commit is contained in:
AbegaM
2024-02-14 16:32:35 +03:00
parent 80490c0484
commit bfb50e6a7e
3 changed files with 98 additions and 11 deletions

View File

@@ -1,28 +1,37 @@
const { tableService } = require('../services');
const { rowService } = require('../services');
const { dbTables } = require('../constants');
const createDefaultTables = async () => {
//1. Check if the default tables are already created
// check if the default tables are already created
const roleTable = tableService.checkTableExists('_roles');
const usersTable = tableService.checkTableExists('_users');
const rolesPermissionTable =
tableService.checkTableExists('_roles_permissions');
const usersRolesTable = tableService.checkTableExists('_users_roles');
//2. Create default auth tables
if (!roleTable) {
tableService.createTable('_roles', dbTables.roleSchema);
}
if (!usersTable) {
// create the _users table
tableService.createTable('_users', dbTables.userSchema);
}
if (!usersRolesTable) {
// create the _users_roles table
tableService.createTable('_users_roles', dbTables.usersRoleSchema);
}
if (!rolesPermissionTable) {
if (!roleTable && !rolesPermissionTable) {
// create the _role table
tableService.createTable('_roles', dbTables.roleSchema);
// create a default role in the _roles table
const role = rowService.save({
tableName: '_roles',
fields: { name: 'defaultt' },
});
const roleId = role.lastInsertRowid;
// create the _roles_permissions table
tableService.createTable(
'_roles_permissions',
dbTables.rolePermissionSchema,
@@ -33,6 +42,28 @@ const createDefaultTables = async () => {
},
},
);
// fetch all DB tables
const tables = tableService.listTables();
// add permission for the default role (for each db table)
const permissions = [];
for (const table of tables) {
permissions.push({
role_id: roleId,
table_name: table.name,
create: 'false',
read: 'true',
update: 'false',
delete: 'false',
});
}
// store the permissions in the db
rowService.bulkWrite({
tableName: '_roles_permissions',
fields: permissions,
});
}
};

View File

@@ -6,14 +6,14 @@ module.exports = (db) => {
const result = statement.all(
...data.whereStringValues,
data.limit,
data.page
data.page,
);
return result;
},
getById(data) {
const pks = data.pks.split(',');
const placeholders = pks.map((pk) => '?').join(',');
const placeholders = pks.map(() => '?').join(',');
const query = `SELECT ${data.schemaString} FROM ${data.tableName} ${data.extendString} WHERE ${data.tableName}.${data.lookupField} in (${placeholders})`;
const statement = db.prepare(query);
const result = statement.all(...pks);
@@ -48,9 +48,28 @@ module.exports = (db) => {
return result;
},
bulkWrite(data) {
const { tableName, fields } = data;
const fieldNames = Object.keys(fields[0]);
const valueSets = fields.map((row) => Object.values(row));
const placeholders = fieldNames.map(() => '?');
const valuesString = valueSets
.map(() => `(${placeholders.join(',')})`)
.join(',');
const query = `INSERT INTO ${tableName} (${fieldNames
.map((field) => `'${field}'`)
.join(', ')}) VALUES ${valuesString}`;
const statement = db.prepare(query);
const result = statement.run(...valueSets.flat());
return result;
},
update(data) {
const pks = data.pks.split(',');
const placeholders = pks.map((pk) => '?').join(',');
const placeholders = pks.map(() => '?').join(',');
const query = `UPDATE ${data.tableName} SET ${data.fieldsString} WHERE ${data.lookupField} in (${placeholders})`;
const statement = db.prepare(query);
const result = statement.run(...pks);
@@ -59,7 +78,7 @@ module.exports = (db) => {
delete(data) {
const pks = data.pks.split(',');
const placeholders = pks.map((pk) => '?').join(',');
const placeholders = pks.map(() => '?').join(',');
const query = `DELETE FROM ${data.tableName} WHERE ${data.lookupField} in (${placeholders})`;
const statement = db.prepare(query);
const result = statement.run(...pks);

View File

@@ -85,6 +85,43 @@ module.exports = (db) => {
}
},
listTables(options = {}) {
const { search, ordering, exclude } = options;
let query = `SELECT name FROM sqlite_master WHERE type IN ('table', 'view')`;
// if search is provided, search the tables
// e.g. search=users
if (search) {
query += ` AND name LIKE $searchQuery`;
}
// if exclude is passed don't return the some tables
// e.g. exclude=['_users', '_roles']
if (exclude) {
const excludeTables = exclude.map((field) => `'${field}'`).join(' ,');
query += `AND name NOT IN (${excludeTables});`;
}
// if ordering is provided, order the tables
// e.g. ordering=name (ascending) or ?_ordering=-name (descending)
if (ordering) {
query += ` ORDER BY $ordering`;
}
try {
const tables = db.prepare(query).all({
searchQuery: `%${search}%`,
ordering: `${ordering?.replace('-', '')} ${
ordering?.startsWith('-') ? 'DESC' : 'ASC'
}`,
});
return tables;
} catch (error) {
console.log(error);
}
},
checkTableExists(tableName) {
const query = `SELECT name FROM sqlite_master WHERE type='table' AND name='${tableName}'`;
const result = db.prepare(query).get();