55 lines
2.1 KiB
TypeScript
55 lines
2.1 KiB
TypeScript
|
|
import { UniqueID } from "@repo/rdx-ddd";
|
||
|
|
import { Result } from "@repo/rdx-utils";
|
||
|
|
|
||
|
|
import { Asset } from "../domain/asset.aggregate";
|
||
|
|
import { AssetCatalogError } from "../domain/asset-definition";
|
||
|
|
import type { AssetInput } from "../domain/asset-values";
|
||
|
|
|
||
|
|
import type { IAssetRepository } from "./asset.repository";
|
||
|
|
import { validateAssetReferences } from "./asset.repository";
|
||
|
|
import { mapAssetInput } from "./asset-input.mapper";
|
||
|
|
export class AssetUseCases {
|
||
|
|
constructor(private readonly repository: IAssetRepository) {}
|
||
|
|
get(companyId: string) {
|
||
|
|
const company = UniqueID.create(companyId);
|
||
|
|
if (!company.isSuccess) {
|
||
|
|
return Promise.resolve(Result.fail(new AssetCatalogError("INVALID_REQUEST")));
|
||
|
|
}
|
||
|
|
return this.repository.get(company.data);
|
||
|
|
}
|
||
|
|
save(companyId: string, id: string | undefined, input: AssetInput, 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 AssetCatalogError("INVALID_REQUEST")));
|
||
|
|
}
|
||
|
|
return this.repository.save(company.data, (context) => {
|
||
|
|
const previous = identity?.isSuccess
|
||
|
|
? context.assets.find((asset) => asset.id.equals(identity.data))
|
||
|
|
: undefined;
|
||
|
|
if (id && !previous) {
|
||
|
|
return Result.fail(new AssetCatalogError("ASSET_NOT_FOUND"));
|
||
|
|
}
|
||
|
|
const mapped = mapAssetInput(input, company.data, context, previous);
|
||
|
|
if (!mapped.isSuccess) {
|
||
|
|
return Result.fail(mapped.error);
|
||
|
|
}
|
||
|
|
const references = validateAssetReferences(context, mapped.data.values, previous);
|
||
|
|
if (!references.isSuccess) {
|
||
|
|
return Result.fail(references.error);
|
||
|
|
}
|
||
|
|
const now = new Date().toISOString();
|
||
|
|
return previous
|
||
|
|
? previous.update(mapped.data.values, actor.data, now)
|
||
|
|
: Asset.create(
|
||
|
|
company.data,
|
||
|
|
mapped.data.specification,
|
||
|
|
mapped.data.values,
|
||
|
|
actor.data,
|
||
|
|
now
|
||
|
|
);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|