Creating a Client with Effect and Layer for HTTP Requests
Does doing something like this make sense?
import type { ClientOptions } from "./schemas";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Logger from "effect/Logger";
import * as MyHttpClient from "./services/MyHttpClient.js";
import { withNamespacedLogSpan } from "./utils/logger.js";
export const createClient = (
options: ClientOptions["Encoded"]
) => {
const clientLayer = Layer.mergeAll(
MyHttpClient.layer(options),
Logger.pretty
);
const runtime = ManagedRuntime.make(clientLayer);
const $fetch = (options?: any) =>
Effect.gen(function* () {
const client = yield* MyHttpClient.MyHttpClient;
const response = yield* client.request(options);
if (response?.errors) {
yield* Effect.logError(response);
} else {
yield* Effect.logInfo(response);
}
return response;
}).pipe(Effect.scoped);
const $get = (options?: any) => runtime.runPromise($fetch(options).pipe(withNamespacedLogSpan("Query"));
return {
$get
};
};import type { ClientOptions } from "./schemas";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Logger from "effect/Logger";
import * as MyHttpClient from "./services/MyHttpClient.js";
import { withNamespacedLogSpan } from "./utils/logger.js";
export const createClient = (
options: ClientOptions["Encoded"]
) => {
const clientLayer = Layer.mergeAll(
MyHttpClient.layer(options),
Logger.pretty
);
const runtime = ManagedRuntime.make(clientLayer);
const $fetch = (options?: any) =>
Effect.gen(function* () {
const client = yield* MyHttpClient.MyHttpClient;
const response = yield* client.request(options);
if (response?.errors) {
yield* Effect.logError(response);
} else {
yield* Effect.logInfo(response);
}
return response;
}).pipe(Effect.scoped);
const $get = (options?: any) => runtime.runPromise($fetch(options).pipe(withNamespacedLogSpan("Query"));
return {
$get
};
};