Files
yara724api/src/profile/profile.service.ts
T
SepehrYahyaee 2056412efe fix: harden profile updates and localize public errors in Persian
Preserve actor and user profile fields during partial updates and validate supported personal data.

Add Persian HTTP error handling, validation translations, regression tests, and audit documentation.
2026-11-04 12:03:04 +03:30

88 lines
3.4 KiB
TypeScript

import {
BadRequestException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
import { UserDbService } from "src/users/entities/db-service/user.db.service";
import { ProfileUserRs } from "./dto/user/profile.dto";
import { UpdateUserProfileDtoRq } from "./dto/user/update-profile.dto";
import { jalaliToGregorianDate, toJalaliDate } from "src/helpers/date-jalali";
import { profileDigits } from "src/auth/dto/actor/profile.actor.dto";
@Injectable()
export class ProfileService {
constructor(private readonly userDbService: UserDbService) {}
async getProfileDetail(username: string, userId?: string) {
const userDetail = await this.userDbService.findOne(
userId ? { _id: userId } : { username },
);
if (!userDetail) throw new NotFoundException("حساب کاربری یافت نشد.");
return new ProfileUserRs(userDetail);
}
async updateProfile(
username: string,
update: Record<string, unknown>,
userId?: string,
) {
const allowedFields = ["birthDay", "gender", "city", "state", "address"];
if (
!update ||
typeof update !== "object" ||
Array.isArray(update) ||
Object.keys(update).some((field) => !allowedFields.includes(field))
) {
throw new BadRequestException(
"Only personal profile fields can be updated",
);
}
const values: Record<string, unknown> = Object.fromEntries(
Object.entries(update).map(([key, value]) => [
key,
typeof value === "string" ? value.trim() : value,
]),
);
if (
!Object.keys(values).length ||
Object.values(values).some((value) => value == null)
)
throw new BadRequestException("اطلاعات حساب معتبر نیست.");
if (values.birthDay !== undefined) {
const raw = profileDigits(String(values.birthDay));
if (!/^(?:\d{8}|\d{4}[-/]\d{1,2}[-/]\d{1,2})$/.test(raw))
throw new BadRequestException("تاریخ تولد معتبر نیست.");
const date = jalaliToGregorianDate(raw);
const packed = raw.replace(/[/-]/g, "");
const isJalali = /^1[2345]\d{6}$/.test(packed);
if (
!date ||
(isJalali &&
toJalaliDate(new Date(`${date}T12:00:00Z`)).replace(/\//g, "") !==
packed)
)
throw new BadRequestException("تاریخ تولد معتبر نیست.");
values.birthDay = date;
if (date > new Date().toISOString().slice(0, 10))
throw new BadRequestException("تاریخ تولد نمی‌تواند در آینده باشد.");
}
if (values.gender === "مرد") values.gender = "male";
if (values.gender === "زن") values.gender = "female";
const dto = plainToInstance(UpdateUserProfileDtoRq, values);
const errors = validateSync(dto);
if (errors.length)
throw new BadRequestException(
errors.flatMap((error) => Object.values(error.constraints ?? {})),
);
const filter = userId ? { _id: userId } : { username };
const existing = await this.userDbService.findOneAndUpdate(filter, {
$set: values,
});
if (!existing) throw new NotFoundException("حساب کاربری یافت نشد.");
// The shared DB helper returns the pre-update document. Read the saved values.
return this.getProfileDetail(username, userId);
}
}