Hey guys, I am trying to use <middy> for lambda va...
# help
m
Hey guys, I am trying to use middy for lambda validation. I was also using handler-lib approach before this.( really liked it! ) I tried wrapping middy with handler but it throws callback error. What is the good way of configuring this? I used both of them together because: • cors • I want to format my error responses as in jsend.
I see that middy has both cors and error middleware. But I think i need to look at how validator is handling/ throwing errors to return json response..
a
I just use my own middleware lib https://www.npmjs.com/package/micro-aws-lambda with ajv and typebox for validation
f
@Mr.9715 can you share a snippet of what your handler looks like? I can try reproducing it.
m
Hey @Frank, thanks for reaching out. I created a gist with the code. @Albert Gao, do you have a sample code with ajv?
a
you create the validation function outside of the handler:validateFunc<_SchemaType_>(_schema_: SchemaType) { return ajv.compile<_Static_<_SchemaType_>>(schema); }, Then, you can create your own function to wrap it: function validate(_validateFunc_: ValidateFunction, _data_: any) { const validationResult = ajvUtils.validate(validateFunc, data); if (validationResult.isError) { throw { error: validationResult.error, }; } return validationResult.data; }
m
Hey @Albert Gao, are you using some extended version of ajv. (AjvUtils)... Also, do you pass the entire event object to your validator or destructured body path and queryString?
a
that is just a wrapper for namespacing, so I can type
ajvUtils.
then all options pops up
I have a validation middleware to handle everything passed in, it grabs info from the event object and parse it
m
Thats what I thought, but then I can't find
.validateFunc
😕.
s
Do this to use middy Create a middyMiddleware.js containing { import middy from '@middy/core'; import httpJsonBodyParser from '@middy/http-json-body-parser'; import httpEventNormalizer from '@middy/http-event-normalizer'; import httpErrorHandler from '@middy/http-error-handler'; export default (handler) => middy(handler).use([ httpJsonBodyParser(), httpEventNormalizer(), httpErrorHandler(), ]); } Then in lambad function do this: import commonMiddleware from middyMiddleware'; export async function xxxxxx (event, context) { your code... } after the function do this. export const handler = commonMiddleware(xxxxxx);