Skip to content

Instantly share code, notes, and snippets.

@thelissimus
Last active February 21, 2024 06:50
Show Gist options
  • Save thelissimus/3083b66abf903f748dcad843851ae77f to your computer and use it in GitHub Desktop.
Save thelissimus/3083b66abf903f748dcad843851ae77f to your computer and use it in GitHub Desktop.
Usage of Layer and Config from Effect for DI and configuration.
import { Effect as IO, Config, Context, Layer, pipe } from "effect";
export type ServerConfig = Readonly<{
port: number;
mode: "development" | "production" | "test";
}>;
export class ServerConfigCtx extends Context.Tag("ServerConfigCtx")<ServerConfigCtx, ServerConfig>() {}
const getNodeEnv = Config.literal("development", "production", "test")("NODE_ENV");
export const ServerConfigCtxLive = Layer.effect(ServerConfigCtx)(
pipe(
Config.all([Config.number("PORT"), getNodeEnv]),
Config.map(([port, mode]) => ({ port, mode })),
),
);
export const ServerConfigCtxTest = Layer.effect(ServerConfigCtx)(
pipe(
Config.all([Config.number("TEST_PORT"), getNodeEnv]),
Config.map(([port, mode]) => ({ port, mode })),
),
);
export type JwtConfig = Readonly<{
secret: string;
issuer: string;
expiresIn: string;
cookieExpiresIn: string;
}>;
export class JwtConfigCtx extends Context.Tag("JwtConfigCtx")<JwtConfigCtx, JwtConfig>() {}
export const getJwtConfig = Config.all([
Config.string("SECRET"),
Config.string("ISSUER"),
Config.string("EXPIRES_IN"),
Config.string("COOKIE_EXPIRES_IN"),
]).pipe(Config.nested("JWT"));
export const JwtConfigCtxLive = Layer.effect(JwtConfigCtx)(
pipe(
getJwtConfig,
Config.map(([secret, issuer, expiresIn, cookieExpiresIn]) => ({ secret, issuer, expiresIn, cookieExpiresIn })),
),
);
export const JwtConfigCtxTest = Layer.effect(JwtConfigCtx)(
pipe(
getJwtConfig,
Config.nested("TEST"),
Config.map(([secret, issuer, expiresIn, cookieExpiresIn]) => ({ secret, issuer, expiresIn, cookieExpiresIn })),
),
);
export type MasterConfig = Readonly<{
server: ServerConfig;
jwt: JwtConfig;
}>;
export class MasterConfigCtx extends Context.Tag("MasterConfigCtx")<MasterConfigCtx, MasterConfig>() {}
const getMasterConfig = pipe(
IO.all([ServerConfigCtx, JwtConfigCtx]),
IO.map(([server, jwt]) => ({ server, jwt })),
);
export const MasterConfigCtxLive = Layer.effect(MasterConfigCtx)(getMasterConfig).pipe(
Layer.provide(ServerConfigCtxLive),
Layer.provide(JwtConfigCtxLive),
);
export const MasterConfigCtxTest = Layer.effect(MasterConfigCtx)(getMasterConfig).pipe(
Layer.provide(ServerConfigCtxTest),
Layer.provide(JwtConfigCtxTest),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment