Todo Creation Effect with Error Handling in TypeScript
Given this generator Effect
ts
Would the following be the idiomatic pipe based approach? How can I leverage some more of the Effect API to maybe reduce some of the boiler plate?
const create = (todo: Todo.TodoRequestDto) =>
Effect.gen(function* () {
const { insertedId } = yield* Effect.tryPromise({
try: insertOne(todo as WithoutId<TodoModel>),
catch: (e) => new GenericTodoRepoError(e),
});
if (insertedId == null) {
return yield* Effect.fail(
new GenericTodoRepoError("Failed to insert document"),
);
}
const newTodo = yield* read(insertedId);
if (newTodo == null) {
return yield* Effect.fail(
new GenericTodoRepoError("Failed to read inserted document"),
);
}
return newTodo;
});const create = (todo: Todo.TodoRequestDto) =>
Effect.gen(function* () {
const { insertedId } = yield* Effect.tryPromise({
try: insertOne(todo as WithoutId<TodoModel>),
catch: (e) => new GenericTodoRepoError(e),
});
if (insertedId == null) {
return yield* Effect.fail(
new GenericTodoRepoError("Failed to insert document"),
);
}
const newTodo = yield* read(insertedId);
if (newTodo == null) {
return yield* Effect.fail(
new GenericTodoRepoError("Failed to read inserted document"),
);
}
return newTodo;
});Would the following be the idiomatic pipe based approach? How can I leverage some more of the Effect API to maybe reduce some of the boiler plate?
const create = () =>
Effect.tryPromise({
try: insertOne(todo as WithoutId<TodoModel>),
catch: (e) => new GenericTodoRepoError(e),
}).pipe(
Effect.andThen(({ insertedId }) => {
if (insertedId == null) {
return Effect.fail(
new GenericTodoRepoError("Failed to insert document"),
);
}
return read(insertedId);
}),
Effect.andThen((newTodo) => {
if (newTodo == null) {
return Effect.fail(
new GenericTodoRepoError("Failed to read inserted document"),
);
}
return Effect.succeed(newTodo);
}),
);const create = () =>
Effect.tryPromise({
try: insertOne(todo as WithoutId<TodoModel>),
catch: (e) => new GenericTodoRepoError(e),
}).pipe(
Effect.andThen(({ insertedId }) => {
if (insertedId == null) {
return Effect.fail(
new GenericTodoRepoError("Failed to insert document"),
);
}
return read(insertedId);
}),
Effect.andThen((newTodo) => {
if (newTodo == null) {
return Effect.fail(
new GenericTodoRepoError("Failed to read inserted document"),
);
}
return Effect.succeed(newTodo);
}),
);