Effect CommunityEC
Effect Community12mo ago
4 replies
Zamion101

Issue with Setting Cookies in Middleware Using HttpServerResponse.unsafeSetCookies

Hi everyone.
I'm trying to write a middleware to convert responses into standard format. I need to set Cookies using HttpServerResponse.unsafeSetCookies but for some reason the cookies variable inside HttpServerResponse in appendPreResponseHandler is not compatible with the required type.

I used Iterator, Iterable, tried to make my own but nothing worked.
How should I use this function.

Also why the cookies or cookies.cookies is not compatible in the first place, like it should be easy as HttpServerResponse.json({}).pip(HttpServerResponse.unsafeSetCookies(res.cookies.cookies)).

Here is my middleware:
Effect.gen(function* (_) {
    const textDecoder = new TextDecoder()
    yield* _(HttpApp.appendPreResponseHandler((_req, res) => Effect.gen(function* (_) {

      let body: Record<string, any> = {}
      switch (res.body._tag) {
        case "Uint8Array": {
          // No need to handle errors, Anything returned by the body is already valid JSON
          body = JSON.parse(textDecoder.decode(res.body.body));
          break;
        }
        default: {
          return res
        }
      }

      const cookiesRecord = res.cookies.cookies
      const cookies = Object.keys(cookiesRecord).flatMap((key) => {
        const cookie = cookiesRecord[key]!
        return [
          cookie.name,
          cookie.value,
          cookie.options
        ]
      })

      let response;
      if (res.status >= 400) {
        response = yield* HttpServerResponse.unsafeJson({
          success: false,
          status: res.status,
          error: body.error,
          message: body.message,
          ...omitKeys(body, ['error', 'message', 'status', '_tag'])
        })
      } else {
        response = yield* _(HttpServerResponse.unsafeJson({
          success: true,
          status: res.status,
          ...omitKeys(body, ['error', 'message', 'status', '_tag'])
        }))
      }

      return response.pipe(
        HttpServerResponse.unsafeSetCookies(res.cookies),
        HttpServerResponse.setStatus(res.status)
      )
    })))
Was this page helpful?