43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
|
|
import { UniqueID } from "@repo/rdx-ddd";
|
||
|
|
import { Result } from "@repo/rdx-utils";
|
||
|
|
|
||
|
|
import { Brand, BrandError, type BrandInput } from "../domain/brand.aggregate";
|
||
|
|
|
||
|
|
import type { IBrandRepository } from "./brand.repository";
|
||
|
|
import { mapBrandInput } from "./brand-input.mapper";
|
||
|
|
export class BrandUseCases {
|
||
|
|
constructor(private readonly repository: IBrandRepository) {}
|
||
|
|
list() {
|
||
|
|
return this.repository.list();
|
||
|
|
}
|
||
|
|
save(id: string | undefined, input: BrandInput): Promise<Result<Brand, BrandError>> {
|
||
|
|
if (id && !UniqueID.create(id).isSuccess) {
|
||
|
|
return Promise.resolve(Result.fail<BrandError>(new BrandError("INVALID_REQUEST")));
|
||
|
|
}
|
||
|
|
return this.repository.save((brands) => {
|
||
|
|
const previous = id
|
||
|
|
? brands.find((brand) => brand.id.toPrimitive() === id.toLowerCase())
|
||
|
|
: undefined;
|
||
|
|
if (id && !previous) {
|
||
|
|
return Result.fail(new BrandError("BRAND_NOT_FOUND"));
|
||
|
|
}
|
||
|
|
const mapped = mapBrandInput(input, previous?.builtin ?? false);
|
||
|
|
if (!mapped.isSuccess) {
|
||
|
|
return Result.fail(mapped.error);
|
||
|
|
}
|
||
|
|
if (
|
||
|
|
brands.some(
|
||
|
|
(brand) =>
|
||
|
|
brand !== previous &&
|
||
|
|
brand.name
|
||
|
|
.toPrimitive()
|
||
|
|
.localeCompare(mapped.data.name.toPrimitive(), "en", { sensitivity: "base" }) === 0
|
||
|
|
)
|
||
|
|
) {
|
||
|
|
return Result.fail(new BrandError("NAME_EXISTS"));
|
||
|
|
}
|
||
|
|
return previous ? previous.update(mapped.data) : Brand.create(mapped.data);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|