MCPcopy Create free account
hub / github.com/Effect-TS/effect / toWebHandlerLayerWith

Function toWebHandlerLayerWith

packages/platform/src/HttpApp.ts:266–308  ·  view source on GitHub ↗
(
  layer: Layer.Layer<R, RE>,
  options: {
    readonly toHandler: (
      runtime: Runtime.Runtime<R>
    ) => Effect.Effect<
      Effect.Effect<ServerResponse.HttpServerResponse, E, R | Scope.Scope | ServerRequest.HttpServerRequest>,
      EX
    >
    readonly middleware?: HttpMiddleware | undefined
    readonly memoMap?: Layer.MemoMap | undefined
  }
)

Source from the content-addressed store, hash-verified

264 * @category conversions
265 */
266export const toWebHandlerLayerWith = <E, R, RE, EX>(
267 layer: Layer.Layer<R, RE>,
268 options: {
269 readonly toHandler: (
270 runtime: Runtime.Runtime<R>
271 ) => Effect.Effect<
272 Effect.Effect<ServerResponse.HttpServerResponse, E, R | Scope.Scope | ServerRequest.HttpServerRequest>,
273 EX
274 >
275 readonly middleware?: HttpMiddleware | undefined
276 readonly memoMap?: Layer.MemoMap | undefined
277 }
278): {
279 readonly dispose: () => Promise<void>
280 readonly handler: (request: Request, context?: Context.Context<never> | undefined) => Promise<Response>
281} => {
282 const scope = Effect.runSync(Scope.make())
283 const dispose = () => Effect.runPromise(Scope.close(scope, Exit.void))
284
285 let handlerCache: ((request: Request, context?: Context.Context<never> | undefined) => Promise<Response>) | undefined
286 // build eagerly so the layer is not tied to the lifetime of the first request
287 const handlerPromise = Effect.gen(function*() {
288 const runtime = yield* (options.memoMap
289 ? Layer.toRuntimeWithMemoMap(layer, options.memoMap)
290 : Layer.toRuntime(layer))
291 return handlerCache = toWebHandlerRuntime(runtime)(
292 yield* options.toHandler(runtime),
293 options.middleware
294 )
295 }).pipe(
296 Scope.extend(scope),
297 Effect.runPromise
298 )
299 // avoid an unhandled rejection, requests will still observe the failure
300 handlerPromise.catch(constVoid)
301 function handler(request: Request, context?: Context.Context<never> | undefined): Promise<Response> {
302 if (handlerCache) {
303 return handlerCache(request, context)
304 }
305 return handlerPromise.then((f) => f(request, context))
306 }
307 return { dispose, handler } as const
308}
309
310/**
311 * @since 1.0.0

Callers 1

toWebHandlerLayerFunction · 0.85

Calls 3

toWebHandlerRuntimeFunction · 0.85
makeMethod · 0.65
pipeMethod · 0.65

Tested by

no test coverage detected