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

OrchestrationCommandReceipts.ts

89 lines2.7 KB

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