import { dataSource } from "../../../data-source"; import { webapi } from "../../../entity/user/webapi"; import InternalException from "../../../exceptions/internalException"; import { CreateWebapiCommand, DeleteWebapiCommand, UpdateLastUsageWebapiCommand, UpdateWebapiCommand, } from "./webapiCommand"; export default abstract class WebapiCommandHandler { /** * @description create api * @param {CreateWebapiCommand} createWebapi * @returns {Promise} */ static async create(createWebapi: CreateWebapiCommand): Promise { return await dataSource .createQueryBuilder() .insert() .into(webapi) .values({ token: createWebapi.token, title: createWebapi.title, expiry: createWebapi.expiry, }) .execute() .then((result) => { return result.identifiers[0].token; }) .catch((err) => { throw new InternalException( `Failed creating api${err.code.includes("ER_DUP_ENTRY") ? " due to duplicate entry for column" : ""}`, err ); }); } /** * @description update api * @param {UpdateWebapiCommand} updateWebapi * @returns {Promise} */ static async update(updateWebapi: UpdateWebapiCommand): Promise { return await dataSource .createQueryBuilder() .update(webapi) .set({ title: updateWebapi.title, expiry: updateWebapi.expiry, }) .where("id = :id", { id: updateWebapi.id }) .execute() .then(() => {}) .catch((err) => { throw new InternalException( `Failed updating api${err.code.includes("ER_DUP_ENTRY") ? " due to duplicate entry for column" : ""}`, err ); }); } /** * @description update api usage * @param {UpdateLastUsageWebapiCommand} updateWebapi * @returns {Promise} */ static async updateUsage(updateWebapi: UpdateLastUsageWebapiCommand): Promise { return await dataSource .createQueryBuilder() .update(webapi) .set({ lastUsage: new Date(), }) .where("id = :id", { id: updateWebapi.id }) .execute() .then(() => {}) .catch((err) => { throw new InternalException(`Failed updating api last usage`, err); }); } /** * @description delete api * @param {DeleteWebapiCommand} deleteWebapi * @returns {Promise} */ static async delete(deleteWebapi: DeleteWebapiCommand): Promise { return await dataSource .createQueryBuilder() .delete() .from(webapi) .where("id = :id", { id: deleteWebapi.id }) .execute() .then(() => {}) .catch((err) => { throw new InternalException("Failed deleting api", err); }); } }