2023-09-26 12:03:40 +02:00

97 lines
2.3 KiB
TypeScript

import { Role } from "le-coffre-resources/dist/Admin";
import BaseAdmin from "../BaseAdmin";
export type IGetRolesParams = {
where?: {};
include?: {};
select?: {};
};
export type IPutRoleParams = {
uid: Role["uid"];
rules: Role["rules"];
};
export type IPostRoleParams = {
name: Role["name"];
};
export default class Roles extends BaseAdmin {
private static instance: Roles;
private readonly baseURl = this.namespaceUrl.concat("/roles");
private constructor() {
super();
}
public static getInstance() {
if (!this.instance) {
return new Roles();
} else {
return this.instance;
}
}
public async get(q?: IGetRolesParams): Promise<Role[]> {
const url = new URL(this.baseURl);
if (q) {
const query = { q };
Object.entries(query).forEach(([key, value]) => url.searchParams.set(key, JSON.stringify(value)));
}
try {
return await this.getRequest<Role[]>(url);
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async post(body: IPostRoleParams) {
const url = new URL(this.baseURl);
try {
return await this.postRequest<Role>(url, body);
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async getOne(q?: IGetRolesParams): Promise<Role | null> {
const url = new URL(this.baseURl);
if (q) {
const query = { q };
Object.entries(query).forEach(([key, value]) => url.searchParams.set(key, JSON.stringify(value)));
}
try {
const res = await this.getRequest<Role[]>(url);
if (!res) return null;
if (res.length > 1) throw new Error("More than one role found");
return res[0] ? res[0] : null;
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async getByUid(uid: string, q?: any): Promise<Role> {
const url = new URL(this.baseURl.concat(`/${uid}`));
if (q) Object.entries(q).forEach(([key, value]) => url.searchParams.set(key, JSON.stringify(value)));
try {
return await this.getRequest<Role>(url);
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async put(uid: string, body: IPutRoleParams): Promise<Role> {
const url = new URL(this.baseURl.concat(`/${uid}`));
try {
return await this.putRequest<Role>(url, body);
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
}