arktypea
arktype14mo ago
dibbo

Generic middleware validator

Hello, I'm trying to write a middleware in my app that handles validating the incoming request body. It currently looks like this
export function validateBody<T extends Type>(
  validator: T
): MiddlewareObj<ValidatedBody<T["infer"]>> {
  return {
    before: async ({ event }: Request) => {
      if (!event.body) return { statusCode: 400 };
      const result = validator(event.body);
      if (result instanceof type.errors) {
        throw new ClientError(result.summary);
      }
      event.body = result;
    },
  };
}

The return type means that in my handler body comes through with the correct type definition given by the validator, e.g.
const schema = type({name:"string"}}
const handleRequest = middy()
  .use(validateBody(schema))
  .handler(async ({ body }) => {
    // body.name === string!
  });


This has worked nicely so far, but unfortunately with larger schemas I'm getting a Type instantiation is excessively deep and possibly infinite error when calling validateBody.

I've read answers to similar questions questionsFunction which receives a arktype's 'type' and questionsProperty 'describe' does not exist on type 'instantiateType<inferTupleExpression<...>, {}>', and tried out some of the suggestions, but I haven't been able to come up with a solution so far.

Is there any way to get this working as expected, or is it not possible with the current limitations of Typescript? Am I safer just casting body in the handler to the expected type (since at that point it has passed validation and I know that it conforms to the expected type)?

Any help or suggestions would be greatly appreciated, thanks!
Was this page helpful?