deeplay-io / nice-grpc

A TypeScript gRPC library that is nice to you

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Server Middleware by Method Implementation

pitakill opened this issue · comments

Hi, what a very nice piece of software you have here! Pure fire!

The last couple of weeks I've enjoyed exploring this gRPC framework, nice work by the way.

I'm wondering if is possible to have a Server Middleware by method, and only by Service Implementation.

I have some methods that use almost the same validation, so would be nice to declare a Middleware for only those methods and abstract the validation logic.

Thank you for your effort in building this nice framework.

I'm glad you liked it!

Yes, you can definitely do that, but that doesn't mean you should 🙂

The request is accessible by middleware, but with generic type:

async function* middleware<Request, Response>(
  call: ServerMiddlewareCall<Request, Response>,
  context: CallContext,
) {
  // call.method contains called method's descriptor
  if (call.method.path === '/my.package.MyService/MyMethod') {
    // call.request has type Request | AsyncIterable<Request>
    validate(call.request as MyMethodRequest); // not recommended because type casting is dangerous!
  }
  
  return yield* call.next(call.request, context);
}

Middleware are designed to be agnostic of an actual service. I would recommend simply calling validate function in each of the relevant methods.

That said, it's not written in stone, and I'll think of better ways of doing this. I can imagine other cases where tightly coupled service and middleware could be convenient. But in these cases I'd want to wrap the service implementation with middleware early — not when adding to a server, but before even exporting it from a module.

Thank you for your response, I take it into consideration about how I'm writing the logic for the validation. :-)