import RandExp from "randexp"; const randomCodeTableB = async (ctx) => { try { const { id } = ctx.user; //Generate random code (5 characters) - Current Table(B) const code = new RandExp(/^[0-9]{5}$/).gen(); //check duplicate current table(B) const tableB = await TableB.findAll({ where: { code: { [Op.ne]: null, }, }, attributes: ["code"], }); for (let i = 0; i < tableB.length; i++) { if (tableB[i].code === code) { return await randomCodeTableB(ctx); //Rerandom if duplicate } } //check duplicate with Table A const tableA = await TableA.findAll({ where: { code: { [Op.ne]: null, }, }, attributes: ["code"], }); for (let i = 0; i < tableA.length; i++) { if (tableA[i].code === code) { return await randomCodeTableB(ctx); //Rerandom if duplicate } } //Update code into current lecturer const currentUser = await TableB.findByPk(id); const updatedCode = await currentUser.update({ code: code, }); return (ctx.body = { msg: "success", data: { code: updatedCode.code }, }); } catch (error) { ctx.response.status = 500; return (ctx.body = { error: "Internal Server Error", }); } };