Skip to content

Commit

Permalink
Move function into a separate file
Browse files Browse the repository at this point in the history
  • Loading branch information
kin0992 committed Jan 15, 2025
1 parent d5b7e84 commit eb31366
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 22 deletions.
23 changes: 2 additions & 21 deletions apps/to-do-api/src/adapters/azure/cosmosdb/TaskRepository.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,13 @@
import { Container, ItemDefinition, ItemResponse } from "@azure/cosmos";
import { Container } from "@azure/cosmos";
import * as E from "fp-ts/lib/Either.js";
import * as O from "fp-ts/lib/Option.js";
import * as TE from "fp-ts/lib/TaskEither.js";
import { pipe } from "fp-ts/lib/function.js";
import * as t from "io-ts";

import { TaskCodec } from "../../../domain/Task.js";
import { TaskRepository } from "../../../domain/TaskRepository.js";
import { decodeFromFeed } from "./decode.js";
import { decodeFromFeed, decodeFromItem } from "./decode.js";
import { cosmosErrorToDomainError } from "./errors.js";

// TODO: Move this to a separate file (introduced in another PR)
export const decodeFromItem =
<A, O>(codec: t.Type<A, O>) =>
<T extends ItemDefinition>(item: ItemResponse<T>) =>
pipe(
O.fromNullable(item.resource),
O.map(codec.decode),
// transform Option<Either<L, R>> => Either<L, Option<R>>
O.sequence(E.Applicative),
E.mapLeft(
() =>
new Error(
`Unable to parse the ${item.resource?.id} using codec ${codec.name}`,
),
),
);

export const makeTaskRepository = (container: Container): TaskRepository => ({
get: (id) =>
pipe(
Expand Down
23 changes: 22 additions & 1 deletion apps/to-do-api/src/adapters/azure/cosmosdb/decode.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { FeedResponse } from "@azure/cosmos";
import { FeedResponse, ItemDefinition, ItemResponse } from "@azure/cosmos";
import * as O from "fp-ts/Option";
import * as E from "fp-ts/lib/Either.js";
import { pipe } from "fp-ts/lib/function.js";
import * as t from "io-ts";
Expand All @@ -19,3 +20,23 @@ export const decodeFromFeed =
new Error(`Unable to parse the resources using codec ${codec.name}`),
),
);

/**
* Decode a single resource, extracted from an ItemResponse, using a codec.
* @param codec the io-ts codec to use to decode the resource
*/
export const decodeFromItem =
<A, O>(codec: t.Type<A, O>) =>
<T extends ItemDefinition>(item: ItemResponse<T>) =>
pipe(
O.fromNullable(item.resource),
O.map(codec.decode),
// transform Option<Either<L, R>> => Either<L, Option<R>>
O.sequence(E.Applicative),
E.mapLeft(
() =>
new Error(
`Unable to parse the ${item.resource?.id} using codec ${codec.name}`,
),
),
);

0 comments on commit eb31366

Please sign in to comment.