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

PullRequestReviewGuides.ts

83 lines2.8 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import * as SqlClient from "effect/sql/SqlClient";
7import * as SqlSchema from "effect/sql/SqlSchema";
8​
9import { PullRequestReviewGuide, ThreadPullRequestKey } from "@t3tools/contracts";
10​
11import {
12 PersistenceDecodeError,
13 PersistenceSqlError,
14 type PullRequestReviewGuideRepositoryError,
15} from "./Errors.ts";
16​
17const GuideRow = Schema.Struct({
18 guide: Schema.fromJsonString(PullRequestReviewGuide),
19});
20​
21export class PullRequestReviewGuideRepository extends Context.Service<
22 PullRequestReviewGuideRepository,
23 {
24 readonly get: (
25 key: ThreadPullRequestKey,
26 ) => Effect.Effect<
27 Option.Option<PullRequestReviewGuide>,
28 PullRequestReviewGuideRepositoryError
29 >;
30 readonly put: (
31 key: ThreadPullRequestKey,
32 guide: PullRequestReviewGuide,
33 ) => Effect.Effect<void, PullRequestReviewGuideRepositoryError>;
34 }
35>()("t3/persistence/PullRequestReviewGuides/PullRequestReviewGuideRepository") {}
36​
37const make = Effect.gen(function* () {
38 const sql = yield* SqlClient.SqlClient;
39​
40 const findGuide = SqlSchema.findOneOption({
41 Request: ThreadPullRequestKey,
42 Result: GuideRow,
43 execute: ({ host, repository, number }) =>
44 sql`
45 SELECT guide_json AS "guide"
46 FROM pull_request_review_guides
47 WHERE host = ${host} AND repository = ${repository} AND number = ${number}
48 `,
49 });
50 const encodeGuide = Schema.encodeEffect(Schema.fromJsonString(PullRequestReviewGuide));
51​
52 return PullRequestReviewGuideRepository.of({
53 get: (key) =>
54 findGuide(key).pipe(
55 Effect.map(Option.map((row) => row.guide)),
56 Effect.mapError((cause) =>
57 Schema.isSchemaError(cause)
58 ? PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause)
59 : new PersistenceSqlError({ operation: "getPullRequestReviewGuide", cause }),
60 ),
61 ),
62 put: (key, guide) =>
63 encodeGuide(guide).pipe(
64 Effect.mapError((cause) =>
65 PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause),
66 ),
67 Effect.flatMap((guideJson) =>
68 sql`
69 INSERT INTO pull_request_review_guides (host, repository, number, guide_json)
70 VALUES (${key.host}, ${key.repository}, ${key.number}, ${guideJson})
71 ON CONFLICT (host, repository, number) DO UPDATE SET guide_json = excluded.guide_json
72 `.pipe(
73 Effect.mapError(
74 (cause) => new PersistenceSqlError({ operation: "putPullRequestReviewGuide", cause }),
75 ),
76 ),
77 ),
78 Effect.asVoid,
79 ),
80 });
81});
82​
83export const layer = Layer.effect(PullRequestReviewGuideRepository, make);