61 lines
2.4 KiB
TypeScript
61 lines
2.4 KiB
TypeScript
|
|
import { UniqueID } from "@repo/rdx-ddd";
|
||
|
|
import { Result } from "@repo/rdx-utils";
|
||
|
|
|
||
|
|
import { Resource } from "../domain/resource.aggregate";
|
||
|
|
import { ResourceCatalogError } from "../domain/resource-definition";
|
||
|
|
import type { ResourceInput } from "../domain/resource-values";
|
||
|
|
|
||
|
|
import type { IResourceRepository } from "./resource.repository";
|
||
|
|
import { mapResourceInput } from "./resource-input.mapper";
|
||
|
|
export class ResourceUseCases {
|
||
|
|
constructor(private readonly repository: IResourceRepository) {}
|
||
|
|
get(companyId: string) {
|
||
|
|
const company = UniqueID.create(companyId);
|
||
|
|
if (!company.isSuccess) {
|
||
|
|
return Promise.resolve(Result.fail(new ResourceCatalogError("INVALID_REQUEST")));
|
||
|
|
}
|
||
|
|
return this.repository.get(company.data);
|
||
|
|
}
|
||
|
|
save(companyId: string, id: string | undefined, input: ResourceInput, actorId: string) {
|
||
|
|
const company = UniqueID.create(companyId);
|
||
|
|
const actor = UniqueID.create(actorId);
|
||
|
|
const identity = id ? UniqueID.create(id) : undefined;
|
||
|
|
if (!(company.isSuccess && actor.isSuccess) || (identity && !identity.isSuccess)) {
|
||
|
|
return Promise.resolve(Result.fail(new ResourceCatalogError("INVALID_REQUEST")));
|
||
|
|
}
|
||
|
|
return this.repository.save(company.data, (context) => {
|
||
|
|
const previous = identity?.isSuccess
|
||
|
|
? context.resources.find((resource) => resource.id.equals(identity.data))
|
||
|
|
: undefined;
|
||
|
|
if (id && !previous) {
|
||
|
|
return Result.fail(new ResourceCatalogError("RESOURCE_NOT_FOUND"));
|
||
|
|
}
|
||
|
|
const mapped = mapResourceInput(input, company.data, context, previous);
|
||
|
|
if (!mapped.isSuccess) {
|
||
|
|
return Result.fail(mapped.error);
|
||
|
|
}
|
||
|
|
if (
|
||
|
|
context.resources.some(
|
||
|
|
(item) =>
|
||
|
|
!item.id.equals(previous?.id) &&
|
||
|
|
item.values.toPrimitive().templateId === mapped.data.values.toPrimitive().templateId &&
|
||
|
|
item.values.name.toPrimitive().toLocaleLowerCase("es") ===
|
||
|
|
mapped.data.values.name.toPrimitive().toLocaleLowerCase("es")
|
||
|
|
)
|
||
|
|
) {
|
||
|
|
return Result.fail(new ResourceCatalogError("NAME_EXISTS"));
|
||
|
|
}
|
||
|
|
const now = new Date().toISOString();
|
||
|
|
return previous
|
||
|
|
? previous.update(mapped.data.values, actor.data, now)
|
||
|
|
: Resource.create(
|
||
|
|
company.data,
|
||
|
|
mapped.data.specification,
|
||
|
|
mapped.data.values,
|
||
|
|
actor.data,
|
||
|
|
now
|
||
|
|
);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|