43 lines
1.9 KiB
TypeScript
43 lines
1.9 KiB
TypeScript
|
|
import { UniqueID } from "@repo/rdx-ddd";
|
||
|
|
import { Result } from "@repo/rdx-utils";
|
||
|
|
|
||
|
|
import { RemoteConnection } from "../domain/remote-connection.aggregate";
|
||
|
|
import type { RemoteConnectionInput } from "../domain/remote-connection-values";
|
||
|
|
import { RemoteConnectionError } from "../domain/remote-connection-values";
|
||
|
|
|
||
|
|
import type { IRemoteConnectionRepository } from "./remote-connection.repository";
|
||
|
|
import { mapRemoteInput } from "./remote-connection-input.mapper";
|
||
|
|
export class RemoteConnectionUseCases {
|
||
|
|
constructor(private readonly repository: IRemoteConnectionRepository) {}
|
||
|
|
get(companyId: string) {
|
||
|
|
const company = UniqueID.create(companyId);
|
||
|
|
return company.isSuccess
|
||
|
|
? this.repository.get(company.data)
|
||
|
|
: Promise.resolve(Result.fail(new RemoteConnectionError("INVALID_REQUEST")));
|
||
|
|
}
|
||
|
|
save(companyId: string, id: string | undefined, input: RemoteConnectionInput, 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 RemoteConnectionError("INVALID_REQUEST")));
|
||
|
|
}
|
||
|
|
return this.repository.save(company.data, (context) => {
|
||
|
|
const previous = identity?.isSuccess
|
||
|
|
? context.connections.find((item) => item.id.equals(identity.data))
|
||
|
|
: undefined;
|
||
|
|
if (id && !previous) {
|
||
|
|
return Result.fail(new RemoteConnectionError("REMOTE_CONNECTION_NOT_FOUND"));
|
||
|
|
}
|
||
|
|
const values = mapRemoteInput(input, context, previous);
|
||
|
|
if (!values.isSuccess) {
|
||
|
|
return Result.fail(values.error);
|
||
|
|
}
|
||
|
|
const now = new Date().toISOString();
|
||
|
|
return previous
|
||
|
|
? previous.update(values.data, actor.data, now)
|
||
|
|
: RemoteConnection.create(company.data, values.data, actor.data, now);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|