:orange_book: Another tutorial created by <@U02H0K...
# guide
j
📙 Another tutorial created by @manitej! This time it’s about how to use Middy to validate the requests and responses in your serverless APIs. https://serverless-stack.com/examples/how-to-use-middy-to-validate-your-serverless-api-requests.html Here’s the sample repo for it: https://github.com/serverless-stack/serverless-stack/tree/master/examples/middy-validator You can also try it by running:
ö
Nice one, I like middy a lot, however, middy’s TS support is really poor. @thdxr Wondering what libs you use in Lambda for handling common non-business logic such as deserialization, serialization, validation etc.
d
@Ömer Toraman I’m in exactly the same position. I have request/response types which I share between my functions and frontend. However, when you add middy into the mix, there’s no way of enforcing the types due to the way middleware works. Would love to know how other people are achieving this.
t
I also don't like middy too much because of TS confusion. I prefer composition over middleware wrappers. I use AJV directly
ö
Do you use anything specific for composing? @thdxr
@Dan Greaves I guess there is no solution to creating types and overriding the middy’s and/or giving up using
aws-lambda
package types
d
Yeah I think just due to the way that middleware is constructed, with two way flows, it’s impossible to type properly. I’m definitely leaning towards keeping things simple and just directly calling whatever validation or helpers I need in the function itself. An example would be like
checkAccountActive(context)
. You could put that at the top of your function, and it will throw an exception if not active, but then you need to catch it in your function to return the response which matches your error response type. At the moment, I’m repeating that logic in basically every function, so not quite sure how to improve it.
ö
I guess it is possible, but beyond my TS knowledge.
Check this out to get an idea how it is done using composition, tho it is not perfect as well: https://github.com/dbartholomae/lambda-middleware I would use this over middy if it was more active
I mean I’m not sure, we have 900 lambdas so some common logic wud be good lol
t
You can theoretically type it right, but it's tricky and requires middy to work slightly differently
Maybe I'll write something at some point, I like doing freaky stuff with typescript
ö
That would be great Dax
Do u use anything for composing?
s
I like to generate models from schema with zod library and share them between backend and frontend using tsconfig paths mapping.
s
Came here to back zod too. Honestly, it is the way.
Also look at trpc project for some inspiration of its capabilities.
Unlocks end to end backend/frontend typing and validation. Luurvly.
t
Zod is pretty great