Effect CommunityEC
Effect Community•17mo ago•
17 replies
Simon

Seeking Help with AsyncLocalStorage Middleware in Effect-TS

Hi everyone 👋 I am new to Effect-TS and I'm currently attempting to replicate the features of my Koa app.

One of the features it has is AsyncLocalStorage. I use it to create a request context containing things like the users preferred language (basically, data that is OK if they are missing, but also are useful for my app).

I was looking into the documentation on middlewares and thought this would be a piece of cake, but unfortunately it doesn't seem to be.

What I am trying to accomplish:

import { AsyncLocalStorage } from 'async_hooks'
import { Context } from 'koa'

export interface RequestContext {
  id: string;
  ...
}

export const asyncLocalStorage = new AsyncLocalStorage<RequestContext>()

export const requestContextMiddleware = async (ctx: Context, next: () => Promise<void>) => {
  ... get id from header or create anew
  ... get other stuff
  await asyncLocalStorage.run({ id, ...otherStuff }, async () => {
    return await next()
  })
}

My "attempt":

export const asyncLocalStorage = new AsyncLocalStorage();

export const requestContextMiddleware = HttpMiddleware.make((app) => {
    return Effect.gen(function* () {
      const req = yield* HttpServerRequest.HttpServerRequest;
      const acceptLanguage = req.headers["accept-language"];
      const preferredLanguage = req.headers["x-language"];
      ... get other stuff
      return yield* asyncLocalStorage.run({ id, ...otherStuff  }, () => app);
    });
});

I understand that the app also needs to be yielded, but that doesn't seem to be possible no matter how i write it. When I add it as is above, I get error:

error: "yield" is a reserved word and cannot be used in strict mode


When actually running my app

1) Is it possible to accomplish this within effect/platform? If yes, what would be the Effect way of doing it?
2) Is there any tips you have for me that will make my transition easier? any concepts i need to really nail down?
Was this page helpful?