|
| 1 | +import { Effect, Layer } from "effect"; |
| 2 | +import { utcDateTimeFromDate } from "../../lib/time/utc.ts"; |
| 3 | +import { DraftNotFoundError } from "../errors.ts"; |
| 4 | +import { |
| 5 | + DraftService, |
| 6 | + type DraftServiceApi, |
| 7 | + type DraftServiceDependencies, |
| 8 | +} from "./service.ts"; |
| 9 | +import type { DraftStoreApi } from "./store.ts"; |
| 10 | +import { |
| 11 | + validateDescription, |
| 12 | + validateDraftId, |
| 13 | + validateStackId, |
| 14 | + validateStateId, |
| 15 | + validateTitle, |
| 16 | +} from "./validation.ts"; |
| 17 | + |
| 18 | +export const makeDraftService = ( |
| 19 | + draftStore: DraftStoreApi, |
| 20 | + dependencies: DraftServiceDependencies, |
| 21 | +): DraftServiceApi => ({ |
| 22 | + listDrafts: () => draftStore.list(), |
| 23 | + |
| 24 | + getDraft: (draftId) => |
| 25 | + Effect.gen(function* () { |
| 26 | + const validatedId = yield* validateDraftId(draftId); |
| 27 | + const draft = yield* draftStore.findById(validatedId); |
| 28 | + |
| 29 | + if (draft === null) { |
| 30 | + return yield* Effect.fail( |
| 31 | + new DraftNotFoundError({ |
| 32 | + draftId: validatedId, |
| 33 | + }), |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + return draft; |
| 38 | + }), |
| 39 | + |
| 40 | + createDraft: (input) => |
| 41 | + Effect.gen(function* () { |
| 42 | + const title = yield* validateTitle(input.title); |
| 43 | + const description = yield* validateDescription(input.description ?? ""); |
| 44 | + |
| 45 | + if (input.stateId !== undefined) { |
| 46 | + yield* validateStateId(input.stateId); |
| 47 | + } |
| 48 | + |
| 49 | + if (input.stackId !== undefined && input.stackId !== null) { |
| 50 | + yield* validateStackId(input.stackId); |
| 51 | + } |
| 52 | + |
| 53 | + const timestamp = utcDateTimeFromDate(dependencies.now()); |
| 54 | + |
| 55 | + return yield* draftStore.createWithResolvedStateAndStack({ |
| 56 | + id: dependencies.generateId(), |
| 57 | + title, |
| 58 | + description, |
| 59 | + stateId: input.stateId, |
| 60 | + stackId: input.stackId, |
| 61 | + createdAt: timestamp, |
| 62 | + updatedAt: timestamp, |
| 63 | + }); |
| 64 | + }), |
| 65 | +}); |
| 66 | + |
| 67 | +export const DraftServiceLive = ( |
| 68 | + draftStore: DraftStoreApi, |
| 69 | + dependencies: DraftServiceDependencies, |
| 70 | +): Layer.Layer<DraftService> => |
| 71 | + Layer.succeed(DraftService, makeDraftService(draftStore, dependencies)); |
0 commit comments