Skip to content

Instantly share code, notes, and snippets.

@kiritocode1
Created August 3, 2025 19:09
Show Gist options
  • Save kiritocode1/cf11e5ab40f7bc23591e8d2475dae171 to your computer and use it in GitHub Desktop.
Save kiritocode1/cf11e5ab40f7bc23591e8d2475dae171 to your computer and use it in GitHub Desktop.
efefts
import { Effect ,Data} from "effect";
import { Schema } from "@effect/schema";
interface Todo{
id: number;
title: string;
}
const TodosSchema = Schema.Array(
Schema.Struct({
id: Schema.Number,
title: Schema.String,
}),
);
class HttpError extends Error {
_tag = 'HttpError';
}
class NotOkError extends Error {
_tag = 'NotOkError';
}
class JsonError extends Error {
_tag = 'JsonError';
}
const getTodo = (id: number) =>
// Will catch any errors and propagate them as UnknownException
Effect.tryPromise({
try: () => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`),
catch: (error) => {
return Effect.fail(new HttpError());
}
}
)
const getJson= (response: Response) => Effect.tryPromise({
try: () => response.json(),
catch: (error) => {
return Effect.fail(new JsonError());
}
});
// Effect<Success , Error , Requirement>
const getTodos2 = Effect.gen(function* (_) {
const response = yield* getTodo(1);
if (!response.ok) {
yield* Effect.fail(new NotOkError());
}
const data = yield* getJson(response);
const parsedData = yield* _(Schema.decode(TodosSchema)(data, {
onExcessProperty: "ignore",
}));
return parsedData;
});
getTodos2.pipe(
Effect.tap(data => {
console.log(data);
}),
Effect.runPromise
)
//! Typescript always assumes the happy path. and gives you to handle the happy path.
async function getTodos() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!response.ok) {
throw new Error("Http Error");
}
const data: Todo = await response.json();
return data;
}
getTodos().then(data => {
console.log(data);
}).catch(error => {
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment