1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-10-18 20:09:08 +02:00
unleash.unleash/src/lib/db/project-store.ts

213 lines
5.9 KiB
TypeScript
Raw Normal View History

import { Knex } from 'knex';
import { Logger, LogProvider } from '../logger';
import NotFoundError from '../error/notfound-error';
import { IProject } from '../types/model';
import {
IProjectHealthUpdate,
IProjectInsert,
2021-10-01 10:59:43 +02:00
IProjectQuery,
IProjectStore,
} from '../types/stores/project-store';
import { DEFAULT_ENV } from '../util/constants';
2021-11-30 14:05:44 +01:00
const COLUMNS = [
'id',
'name',
'description',
'created_at',
'health',
2021-11-30 15:25:52 +01:00
'updated_at',
2021-11-30 14:05:44 +01:00
];
const TABLE = 'projects';
class ProjectStore implements IProjectStore {
private db: Knex;
private logger: Logger;
constructor(db: Knex, getLogger: LogProvider) {
this.db = db;
this.logger = getLogger('project-store.ts');
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
fieldToRow(data): IProjectInsert {
return {
id: data.id,
name: data.name,
description: data.description,
};
}
destroy(): void {}
async exists(id: string): 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;
}
2021-10-01 10:59:43 +02:00
async getAll(query: IProjectQuery = {}): Promise<IProject[]> {
const rows = await this.db
.select(COLUMNS)
.from(TABLE)
2021-10-01 10:59:43 +02:00
.where(query)
.orderBy('name', 'asc');
return rows.map(this.mapRow);
}
async get(id: string): Promise<IProject> {
return this.db
.first(COLUMNS)
.from(TABLE)
.where({ id })
.then(this.mapRow);
}
async hasProject(id: string): 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 updateHealth(healthUpdate: IProjectHealthUpdate): Promise<void> {
await this.db(TABLE)
.where({ id: healthUpdate.id })
2021-11-30 15:25:52 +01:00
.update({ health: healthUpdate.health, updated_at: new Date() });
}
async create(project: IProjectInsert): Promise<IProject> {
const row = await this.db(TABLE)
.insert(this.fieldToRow(project))
.returning('*');
feat: custom project roles (#1220) * wip: environment for permissions * fix: add migration for roles * fix: connect environment with access service * feat: add tests * chore: Implement scaffolding for new rbac * fix: add fake store * feat: Add api endpoints for roles and permissions list * feat: Add ability to provide permissions when creating a role and rename environmentName to name in the list permissions datastructure * fix: Make project roles resolve correctly against new environments permissions structure * fix: Patch migration to also populate permission names * fix: Make permissions actually work with new environments * fix: Add back to get permissions working for editor role * fix: Removed ability to set role type through api during creation - it's now always custom * feat: Return permissions on get role endpoint * feat: Add in support for updating roles * fix: Get a bunch of tests working and delete a few that make no sense anymore * chore: A few small cleanups - remove logging and restore default on dev server config * chore: Refactor role/access stores into more logical domains * feat: Add in validation for roles * feat: Patch db migration to handle old stucture * fix: migration for project roles * fix: patch a few broken tests * fix: add permissions to editor * fix: update test name * fix: update user permission mapping * fix: create new user * fix: update root role test * fix: update tests * feat: Validation now works when updating a role * fix: Add in very barebones down migration for rbac so that tests work * fix: Improve responses from role resolution - getting a non existant role will throw a NotFound error * fix: remove unused permissions * fix: add test for connecting roles and deleting project * fix: add test for adding a project member with a custom role * fix: add test for changing user role * fix: add guard for deleting role if the role is in use * fix: alter migration * chore: Minor code cleanups * chore: Small code cleanups * chore: More minor cleanups of code * chore: Trim some dead code to make the linter happy * feat: Schema validation for roles * fix: setup permission for variant * fix: remove unused import * feat: Add cascading delete for role_permissions when deleting a role * feat: add configuration option for disabling legacy api * chore: update frontend to beta version * 4.6.0-beta.0 * fix: export default project constant * fix: update snapshot * fix: module pattern ../../lib * fix: move DEFAULT_PROJECT to types * fix: remove debug logging * fix: remove debug log state * fix: Change permission descriptions * fix: roles should have unique name * fix: root roles should be connected to the default project * fix: typo in role-schema.ts * fix: Role permission empty string for non environment type * feat: new permission for moving project * fix: add event for changeProject * fix: Removing a user from a project will now check to see if that project has an owner, rather than checking if any project has an owner * fix: add tests for move project * fix: Add in missing create/delete tag permissions * fix: Removed duplicate impl caused by multiple good samaritans putting it back in! * fix: Trim out add tag permissions, for now at least * chore: Trim out new add and delete tag permissions - we're going with update feature instead * chore: update frontend * 4.6.0-beta.1 * feat: Prevent editing of built in roles * fix: Patch an issue where permissions for variants/environments didn't match the front end * fix: lint Co-authored-by: Ivar Conradi Østhus <ivarconr@gmail.com> Co-authored-by: Fredrik Oseberg <fredrik.no@gmail.com>
2022-01-13 11:14:17 +01:00
return this.mapRow(row[0]);
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
async update(data): Promise<void> {
try {
await this.db(TABLE)
.where({ id: data.id })
.update(this.fieldToRow(data));
} catch (err) {
this.logger.error('Could not update project, error: ', err);
}
}
async importProjects(projects: IProjectInsert[]): Promise<IProject[]> {
const rows = await this.db(TABLE)
.insert(projects.map(this.fieldToRow))
.returning(COLUMNS)
.onConflict('id')
.ignore();
if (rows.length > 0) {
await this.addDefaultEnvironment(rows);
return rows.map(this.mapRow);
}
return [];
}
async addDefaultEnvironment(projects: any[]): Promise<void> {
const environments = projects.map((p) => ({
project_id: p.id,
environment_name: DEFAULT_ENV,
}));
await this.db('project_environments')
.insert(environments)
.onConflict(['project_id', 'environment_name'])
.ignore();
}
async deleteAll(): Promise<void> {
await this.db(TABLE).del();
}
async delete(id: string): Promise<void> {
try {
await this.db(TABLE).where({ id }).del();
} catch (err) {
this.logger.error('Could not delete project, error: ', err);
}
}
async deleteEnvironmentForProject(
id: string,
environment: string,
): Promise<void> {
await this.db('project_environments')
.where({
project_id: id,
environment_name: environment,
})
.del();
}
async addEnvironmentToProject(
id: string,
environment: string,
): Promise<void> {
await this.db('project_environments')
.insert({ project_id: id, environment_name: environment })
.onConflict(['project_id', 'environment_name'])
.ignore();
}
async getEnvironmentsForProject(id: string): Promise<string[]> {
return this.db('project_environments')
.where({
project_id: id,
})
.pluck('environment_name');
}
async getMembers(projectId: string): Promise<number> {
const rolesFromProject = this.db('role_permission')
.select('role_id')
.distinct()
.where({ project: projectId });
const numbers = await this.db('role_user')
.countDistinct('user_id as members')
.whereIn('role_id', rolesFromProject)
.first();
const { members } = numbers;
if (typeof members === 'string') {
return parseInt(members, 10);
}
return members;
}
2021-08-27 10:10:14 +02:00
async count(): Promise<number> {
return this.db
.count('*')
.from(TABLE)
.then((res) => Number(res[0].count));
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
mapRow(row): IProject {
if (!row) {
throw new NotFoundError('No project found');
}
return {
id: row.id,
name: row.name,
description: row.description,
createdAt: row.created_at,
health: row.health || 100,
2021-11-30 15:25:52 +01:00
updatedAt: row.updated_at || new Date(),
};
}
}
export default ProjectStore;
module.exports = ProjectStore;