Skip to content

Commit

Permalink
Extract a Redis layer
Browse files Browse the repository at this point in the history
  • Loading branch information
thewilkybarkid committed Dec 4, 2023
1 parent 8c40b8d commit 8a6751a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
9 changes: 7 additions & 2 deletions src/Redis.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Context, Data, Effect } from 'effect'
import type IoRedis from 'ioredis'
import { Context, Data, Effect, Layer } from 'effect'
import IoRedis from 'ioredis'

export type Redis = IoRedis.Redis

Expand All @@ -9,6 +9,11 @@ export class RedisError extends Data.TaggedError('RedisError')<{
readonly error: unknown
}> {}

export const layer: Layer.Layer<never, never, Redis> = Layer.scoped(
Redis,
Effect.acquireRelease(Effect.succeed(new IoRedis.Redis()), redis => Effect.sync(() => redis.disconnect())),
)

export const ping = (): Effect.Effect<Redis, RedisError, 'PONG'> =>
Effect.gen(function* (_) {
const redis = yield* _(Redis)
Expand Down
8 changes: 2 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { HttpClient, HttpServer, Runtime } from '@effect/platform-node'
import { Schema } from '@effect/schema'
import { Effect, Layer } from 'effect'
import IoRedis from 'ioredis'
import { createServer } from 'node:http'
import * as CoarNotify from './CoarNotify.js'
import { ConfigLive } from './Config.js'
Expand Down Expand Up @@ -112,13 +111,10 @@ const serve = HttpServer.router.empty.pipe(

const ServerLive = HttpServer.server.layer(() => createServer(), { port: 3000 })

const RedisLive = Layer.effect(
Redis.Redis,
Effect.acquireRelease(Effect.succeed(new IoRedis.Redis()), redis => Effect.sync(() => redis.disconnect())),
)
const RedisLive = Redis.layer

const HttpLive = Layer.scopedDiscard(serve).pipe(
Layer.provide(Layer.mergeAll(ConfigLive, HttpClient.client.layer, ServerLive, RedisLive)),
)

Layer.launch(HttpLive).pipe(Effect.tapErrorCause(Effect.logError), Effect.scoped, Runtime.runMain)
Layer.launch(HttpLive).pipe(Effect.tapErrorCause(Effect.logError), Runtime.runMain)

0 comments on commit 8a6751a

Please sign in to comment.