Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OrchestrationCommandReceipts.ts

90 lines2.8 KB

1import * as SqlClient from "effect/unstable/sql/SqlClient";
2import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5​
6import { toPersistenceSqlError } from "../Errors.ts";
7​
8import {
9 GetByCommandIdInput,
10 OrchestrationCommandReceipt,
11 OrchestrationCommandReceiptRepository,
12 type OrchestrationCommandReceiptRepositoryShape,
13} from "../Services/OrchestrationCommandReceipts.ts";
14​
15const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
16 const sql = yield* SqlClient.SqlClient;
17​
18 const upsertReceiptRow = SqlSchema.void({
19 Request: OrchestrationCommandReceipt,
20 execute: (receipt) =>
21 sql`
22 INSERT INTO orchestration_command_receipts (
23 command_id,
24 aggregate_kind,
25 aggregate_id,
26 accepted_at,
27 result_sequence,
28 status,
29 error
30 )
31 VALUES (
32 ${receipt.commandId},
33 ${receipt.aggregateKind},
34 ${receipt.aggregateId},
35 ${receipt.acceptedAt},
36 ${receipt.resultSequence},
37 ${receipt.status},
38 ${receipt.error}
39 )
40 ON CONFLICT (command_id)
41 DO UPDATE SET
42 aggregate_kind = excluded.aggregate_kind,
43 aggregate_id = excluded.aggregate_id,
44 accepted_at = excluded.accepted_at,
45 result_sequence = excluded.result_sequence,
46 status = excluded.status,
47 error = excluded.error
48 `,
49 });
50​
51 const findReceiptByCommandId = SqlSchema.findOneOption({
52 Request: GetByCommandIdInput,
53 Result: OrchestrationCommandReceipt,
54 execute: ({ commandId }) =>
55 sql`
56 SELECT
57 command_id AS "commandId",
58 aggregate_kind AS "aggregateKind",
59 aggregate_id AS "aggregateId",
60 accepted_at AS "acceptedAt",
61 result_sequence AS "resultSequence",
62 status,
63 error
64 FROM orchestration_command_receipts
65 WHERE command_id = ${commandId}
66 `,
67 });
68​
69 const upsert: OrchestrationCommandReceiptRepositoryShape["upsert"] = (receipt) =>
70 upsertReceiptRow(receipt).pipe(
71 Effect.mapError(toPersistenceSqlError("OrchestrationCommandReceiptRepository.upsert:query")),
72 );
73​
74 const getByCommandId: OrchestrationCommandReceiptRepositoryShape["getByCommandId"] = (input) =>
75 findReceiptByCommandId(input).pipe(
76 Effect.mapError(
77 toPersistenceSqlError("OrchestrationCommandReceiptRepository.getByCommandId:query"),
78 ),
79 );
80​
81 return {
82 upsert,
83 getByCommandId,
84 } satisfies OrchestrationCommandReceiptRepositoryShape;
85});
86​
87export const OrchestrationCommandReceiptRepositoryLive = Layer.effect(
88 OrchestrationCommandReceiptRepository,
89 makeOrchestrationCommandReceiptRepository,
90);