Create a Type-Safe Request Handler with Zod and Express
In this exercise, we'll create a runtime-safe and type-safe integration point between the Zod and Express libraries.
Spoiler alert: This is going to involve some hardcore TypeScript!
The Express App
0:00 In this exercise, we're going to be creating an integration point between two external libraries. This is some of the most hardcore and awesome, useful TypeScript you can do. We're going to be putting together Zod and Express. I'm going to show you how we're going to do that.
0:18 We have an Express app here. What we're doing is we're basically saying makeTypeSafeHandler, what it's going to take in, an object for the query here and an object for the body. Then, inside the request here, request.query is going to be typed to this thing here, to query. Then request.body is going to be typed to this name string here.
0:47 It's basically making a type and runtime-safe handler. What it's currently doing is there's no generics on it anywhere. We've got z.Schema and z.Schema on the body here. We've got some RequestHandlers, which we're getting from Express.
1:05 If you remember the exercises that we did on those, then you should remember that these take some generics. Ideally, what we want to do is mash them together somehow and make a RequestHandler that builds on all of the things that we understand that this can do.
1:25 You should be able to remember the generic structure for RequestHandler and maybe for z.Schema too. I am not going to give you too much information here. There's one more thing too, which is you should default these to any if no config has been passed in.
1:44 You see, in this one, we haven't passed in body or query. request.query should be any. request.body should be any as well. I think that's everything. This is going to be a complicated one. Good luck.