refactor: throw common error with util function instead

This commit is contained in:
Methapon Metanipat 2024-10-03 09:41:47 +07:00
parent 68f9dc203e
commit 4de0e1da87
12 changed files with 67 additions and 142 deletions

View file

@ -36,7 +36,7 @@ import {
createPermCondition,
} from "../services/permission";
import { connectOrDisconnect, connectOrNot, whereAddressQuery } from "../utils/relation";
import { notFoundError, relationError } from "../utils/error";
import { isUsedError, notFoundError, relationError } from "../utils/error";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
@ -638,17 +638,13 @@ export class UserController extends Controller {
where: { id: userId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "User cannot be found.", "userNotFound");
}
if (!record) throw notFoundError("User");
await Promise.all([
...record.branch.map(async ({ branch }) => await permissionCheck(req.user, branch)),
]);
if (record.status !== Status.CREATED) {
throw new HttpError(HttpStatus.FORBIDDEN, "User is in used.", "userInUsed");
}
if (record.status !== Status.CREATED) throw isUsedError("User");
await deleteFolder(fileLocation.user.profile(userId));
await deleteFolder(fileLocation.user.attachment(userId));
@ -686,9 +682,7 @@ async function getUserCheckPerm(user: RequestWithUser["user"], userId: string) {
where: { id: userId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "User cannot be found.", "userNotFound");
}
if (!record) throw notFoundError("User");
await Promise.all(record.branch.map(async ({ branch }) => await permissionCheck(user, branch)));
}
@ -702,9 +696,7 @@ export class UserProfileController extends Controller {
where: { id: userId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "User cannot be found.", "userNotFound");
}
if (!record) throw notFoundError("User");
return await listFile(fileLocation.user.profile(userId));
}
@ -739,9 +731,7 @@ export class UserAttachmentController extends Controller {
where: { id: userId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "User cannot be found.", "userNotFound");
}
if (!record) throw notFoundError("User");
const list = await listFile(fileLocation.user.attachment(userId));