refactor: helper function

This commit is contained in:
Methapon Metanipat 2024-09-11 18:04:53 +07:00
parent a7cafd25d0
commit 7b002451c3

View file

@ -37,6 +37,7 @@ import {
createPermCondition,
} from "../services/permission";
import { connectOrDisconnect, connectOrNot, whereAddressQuery } from "../utils/relation";
import { notFoundError, relationError } from "../utils/error";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
@ -308,7 +309,7 @@ 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");
return record;
}
@ -328,27 +329,9 @@ export class UserController extends Controller {
where: { username: body.username },
}),
]);
if (body.provinceId && !province) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Province cannot be found.",
"relationProvinceNotFound",
);
}
if (body.districtId && !district) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"District cannot be found.",
"relationDistrictNotFound",
);
}
if (body.subDistrictId && !subDistrict) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Sub-district cannot be found.",
"relationSubDistrictNotFound",
);
}
if (body.provinceId && !province) throw relationError("Province");
if (body.districtId && !district) throw relationError("District");
if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict");
if (branch.length === 0) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
@ -357,7 +340,7 @@ export class UserController extends Controller {
);
}
await Promise.all([...branch.map(async (branch) => await permissionCheck(req.user, branch))]);
await Promise.all(branch.map((branch) => permissionCheck(req.user, branch)));
if (user) {
throw new HttpError(HttpStatus.BAD_REQUEST, "User exists.", "userExists");
@ -489,27 +472,10 @@ export class UserController extends Controller {
},
}),
]);
if (!user) {
throw new HttpError(HttpStatus.NOT_FOUND, "User cannot be found.", "userNotFound");
}
if (body.provinceId && !province)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Province cannot be found.",
"missing_or_invalid_parameter",
);
if (body.districtId && !district)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"District cannot be found.",
"missing_or_invalid_parameter",
);
if (body.subDistrictId && !subDistrict)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Sub-district cannot be found.",
"missing_or_invalid_parameter",
);
if (!user) throw notFoundError("User");
if (body.provinceId && !province) throw relationError("Province");
if (body.districtId && !district) throw relationError("District");
if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict");
if (body.branchId && branch.length === 0) {
throw new HttpError(
HttpStatus.BAD_REQUEST,