Effect CommunityEC
Effect Community9mo ago
6 replies
wewell

Applying Idempotency Middleware to HttpApi Endpoints

Hey, I'm writing an HttpMiddleware and I can't find a way to apply it to some endpoints created by
HttpApi


More precisely, I'm writing an IdempotencyMiddleware that looks like this:

import { HttpMiddleware, HttpServerRequest } from '@effect/platform';
import { Effect, Exit } from 'effect';

const IdempotencyMiddleware = HttpMiddleware.make((app) =>
  Effect.gen(function* () {
    const req = yield* HttpServerRequest.HttpServerRequest;
    const idempotencyKey = req.headers['Idempotency-Key'];

    if (!idempotencyKey) {
      return yield* app;
    }

    const tx = yield* createIdempotencyTransaction(idempotencyKey);

    return yield* app.pipe(
      Effect.onExit(
        Exit.matchEffect({
          onSuccess: () => {
            yield * tx.commit();
          },
          onFailure: () => {
            yield * tx.rollback();
          },
        })
      )
    );
  })
);


I don't think I can write this with
HttpApiMiddleware
because I need the Effect.onExit to perform some finalization. How could I apply this middleware to my
HttpApi
endpoints ?
Was this page helpful?