Skip to main content
View on YouTube to comment and like!

Syntax Video

Write The Code You Wish Existed | TypeScript + Nitro API Validation Example

Chapter 1 0:00

intro

have you ever been coding in a library or a framework and sometimes you just wish particular function existed or wished a particular function worked in a slightly different way uh I do this all the time and in this video I'm going to walk you through uh one of the utility functions I created for a project that I'm working on um and I forget where I heard this but I I like to think of this as dream code right you you think of what what is the best possible API that could exist for this particular library or framework and then try to make it happen so in this video I'm going to show you an example of that we're going to dive into writing some backend API functions and also we'll get into uh typescript generics so that our Dream code has some really good type safety so let's dive in my name is CJ welcome to [Music] syntax so I've been building out a full stack app with this framework called n which is a full stack view framework

Chapter 2 0:51

what we're working with today

it's essentially like nextjs but for few um and I've been working with it and N is actually built on top of a framework called Nitro and you might have heard of nitro cuz it's also used instead of tan stack start and solid start and Nitro itself is built on top of H3 which are framework agnostic ways for building backend route handlers um and so to show you this example we're actually just going to be using nitro with H3 so it's a little bit paired back we won't be looking at any view code today it's all just backend code so here in my Nitro app I have a couple of endpoints and Nitro is pretty easy to get used to you could think of it kind of like Express or hono it's a way of building uh backend endpoints you can see here in the server folder we have a routes folder and then I have this index. g.s file and this just exports an event handler so Define event handler comes from H3 and it allows us to define a backend event handler and because this file has get in the name this will

Chapter 3 1:29

basic intro to nitro / h3

respond whenever this API receives a git request on the index route and in this case it's just going to respond with the Json object so pretty simple stuff let's see this in action so if I head over here and then just make a get request to Local Host 3000 we get back hello world so it's a very simple inpoint this is what you can do with Nitro and H3 but what we really care about is what's here in our greeting. poost file so this is a file that will respond to post requests on/ greeting and essentially we take in a request body that has a name property on it and we validate it so read validated body is built into H3 essentially it'll stream in that body and then in turn pass it to schema. Safe parse which comes from Zod and then we get back our validation result and if there was a validation error meaning the name property is missing we set the status code to 422 and then just respond with an error but if there was no error we actually use the data and then just respond with a greeting that says hello

Chapter 4 2:16

validating request body

name so to see this in action if we send a greeting with an empty body we can see that we get back this Zod error that says name is required but if we pass in the name and send it it responds with hello name so this is our function but as I've been building out apis with Nu which uses Nitro and H3 behind the scenes uh I've been defining event handlers and this piece right here can get very repetitive and cumbersome right because for every single route where I want to validate the body I have to write this code pretty often I also want to validate the incoming query parameters or validate the Pam that are in the path and you could expect that as I have more and more routes this code is going to be in more and more places so there' be a lot of copy pasting there'd be a lot of code duplication and so this is the one piece that I just couldn't settle with and I wanted something better um and on that topic of dream code really my dream code was is something like this and it's kind of inspired by hono because they have validation middleware but it would be

Chapter 5 3:10

the problem

Chapter 6 3:39

validation dream code

really great if I could do something like this if I could say let's grab the body from event. context. validated and then use that validated body right here and so inside of H3 this context object here you can put anything you want onto it so typically you might have off middlewares that put like session data or user data or other things like that um but because of that you can see that all of this gets the any type so my code isn't even complaining right now because it is possible that this property could exist but this is the kind of code that I want to write and of course I would need to have a custom function so something like Define validated event handler and then that would need access to the schema so we could for instance like pass it in as the first argument and then we could write code that looks like this and so for every other inpoint where we need to validate the incoming request body we could use this little helper function and not have to have this boiler plate in every spot and so this is the dream code that I want to actually implement but we also want it to be type safe right so we'll implement this function and we'll get it working

but then we'll work on type safety and that will deal with some generics so it'll get pretty interesting so let's grab this code that we pulled out because that's going to live inside of Define validated event handler we are essentially creating an abstraction right we're hiding away that validation code because all we care about as programmers is passing in that schema and we want it to take care of the rest so here in the utils folder I have a function defined inside of Define validated event handler it's empty right now but we need to get it working so first of all I'm going to throw this code in here because it will need to run at some point and then this will need to return a call to Define event handler again this is the thing built into H3 that lets us toine these handlers and then I'll move my code inside of there I'll get access to the event make this an async function okay a little bit closer now we need access to that schema so we'll accept it as an argument in this case this will be of type Zod type so that looks good and if we look back over here let's actually import that

Chapter 7 4:57

creating our dream code

function and we can see we're on our way right so we're passing in the schema good but we also want to accept an event handler so our function needs to take in that Handler now I won't add the type for now it's just the any type but this is a function that accepts an event and so what we can do is if the body was valid we can actually just call that Handler that we passed in and then pass it the event and then right before that we can update the context right so right before we call it we can say event.

context. validated is an object where the body is result. dat like so this should work now we don't have any type safety yet right handle is still the any type and if we look back over here it typescript isn't complaining but body and validated are still the any type but if I written everything correctly we should at least have this utility function now so let's try it out so back over here in insomnia if I make a post request to greeting with nobody I get that validation error and if I pass in a valid body it works we get pack the message okay now let's work on getting the actual types to flow through so Handler is just a function that accepts an event if we hover over the event here because we're using Define event handler the types are flowing through so I know that that event object needs to be of type H3 event so I could type this to be a function that takes in an event that is of type H3 event and in this case

Chapter 8 6:54

type safety - overriding event type

just returns anything now I do need to import H3 event from H3 like so so now that's happy now right now I have the return type is any and technically I could just put the actual type on here so you can see Define event handler returns event handler so technically we could specify the type here and that should be fine because now this is actually typed and we can actually pass in that um but what I'm curious about is what is the return type of event handler and there is a utility function built into typescript called return type where you can pass in a function type and it will tell you what the return type is and in this case it's any so under the hood they actually do type it as any because your event handlers could return anything so because of that I am going to instead of specifying it as event handler I'll specify it as a function that takes an event which is of type H3 event and then returns any and the reason I'm doing this is because we will in turn need to override that context type but now the types are a little bit

better because this thing actually has a type and it actually accepts that event which has the correct type so that's great but now I want to override the type of this context property here on the H the event so for now let's Define a type up here called a validated event and this validated event will extend the H3 event but it will be a composite type because we're also going to override the context so here we can say the context is of type H3 context and so if I hover over context here we can see that the type of this is H3 event context and we should be able to get access to that from H3 as well so here I can say context is of type H3 event context and expand the type so here I want to say that it should have a validated property and this validated object should have a body and that body is going to be of type data so it's going to be the resulting data type of safely parsing that incoming request body and so built

into Zod is this z. infer so let's import Zod real quick and if you worked with Zod you know that you can typically pass in some schema here but right now we don't know what that schema is so this is where generics come into play and so what I can say is this validated event will accept a Type S and then we can then use z. infer and pass that type in but you can see typescript is complaining because we need to make sure that s is of the Zod type so here I can say it extends Zod type and so now I have this nice little utility type where I can pass in a Zod type and it's going to give me back this H to the event that has annotated its context here to give it a fully typed validated uh object with the type of that specific body so now if we want to use this type I'm going to use it here instead of H3 events so we'll pass in validated event but we do have to pass in the schema as a type argument and so how are we going to do that we'll actually make our

Chapter 9 9:23

typescript generic zod schema

function itself generic so if I make this generic and it takes in a schema which also extends Zod type now I can use this type right here and the types will flow through so I'll show you on the other side when we're actually calling this function we don't even need to Define it using generics because typescript is smart enough to see that the first argument I pass in is a Zod type and so now it knows what s is and then when it creates this type it's going to know what s is right here to be able to infer that underlying validated type and then the last thing we'll do is just a type assertion so because I put that context. validated. body on there now it is of type validated event so I can grab my type here and then just use a type of assertion that say Hey that event is actually a validated event and if I've done this correctly on the other side the types should now flow through okay so no type errors but if I hover over validated look at that the type has flowed through and if I take a look at body it has the validated type there and

what's great is it's all flowing through from the schema here so if I add more properties on this like favorite number for instance now if I look at the body type that type is flowing through as well but we've done we have our Dream code so now anytime I'm defining an event handler and I need to validate the incoming body all I have to do is pass in the schema and everything else is taken care of but of course we should test it out it should behave exactly as before so if I pass in an empty body we get back that Zod validation error but if I pass in a valid body we get back the response so this is awesome um but we could also take it a step further so right now I'm only validating the body but let's let's let's dream again what if Define validated event handler instead of just taking a single schema what if it took in an object of options where we could say validate the body with this schema and let's just rename this to body schema uh but let's say we want a schema to validate our query parameters so let's call this the query schema and then maybe favorite number is

Chapter 10 11:28

working dream code

Chapter 11 11:48

more dream code

in the query parameters we could Co it from a string to a number and then maybe I also want to pass in this query schema here and so now if this code did work I would have a really easy way to specify my validators for all the different types of things the query the body I could also pass in let's say pams and then it could validate the pams in the path but now Now We're Dreaming right now we should be able to not only extract off body but also extract off the validated query now I'm going to show you how I implemented this but if I've inspired you go off and try to implement this yourself on the surface it could be very easy but I will say that if you want these to be like optional right so sometimes you only want to pass in the body schema sometimes you only want pass in the query schema that's where the typescript generics get a little bit trickier but I encourage you to go try to implement this try to test out your typescript skills but now I'll show you how I implemented this okay this is where things get a little little bit silly with typescript um first of all we now

Chapter 12 13:09

full dream code solution

are accepting in an object called validations that has those three properties right the body query or prams but like I said I want all three of them to be optional because sometimes I only want to validate the query or sometimes I only want to validate the body so we've set those to optional you can then see I have three different type arguments the first one is for the body but it can be undefined right because you might not pass in that schema then we have q which is the query schema and then P which is the pram schema and with typescript generics you can actually assign a default value so here I've set all of them to undefined so by default they're all undefined unless you actually pass in a specific schema for any one of them from there I also defined this validated event type in line so you might not have realized you could do this but your type arguments can also Define types too they don't have to be themselves type arguments and I did this so that way I wouldn't have to pass BQ and P to another type as type arguments but we have the same overridden H3 event and H3 event context

here but here we're using conditionals on the type so if we did pass in a schema for body then B extends Zod type will be true which means the resulting validated body property will be the infer schema from B otherwise if we didn't pass in a body schema it's going to be undefined and the reason I care about this is because on the other side where we're using the code right because if I only pass in a body validation schema I want query and pams to be of the unknown or undefined type I want to get a type error if I try to access validated. query or validated. prams and I didn't pass in a query schema or a pram schema and so we're using this Turner type for each one of these so if we did pass in a schema for it we'll for that type from there it's just a matter of calling all of the validators so I have a map that is keeping track of all of the errors for the body the query and the pams and so if we passed in a schema

for the body then we will read the body run the parser and if it was not successful store that error inside of this map we do that same thing for the query and then also for the router prams but then if it was valid we keep track of it in this map here so we set that validated data for the body we set it for the query and then we set it for the params and then if we have any errors at all we set the status code to 422 and then we show the errors for body prams or query depending on if those were defined and if they exist in the map if there were no errors then we can just grab all of that validated data so right we're storing all of the validated data in this map here so we can use from entries to get an object that will have a body property a query property and a params property if the validated data exists for each one of those okay so there there's a lot of other ways to implement this if you gave it a try and tried to implement yourself I'd love to see how you did it so let me know in the comments but now if we take a look on

the other side we can see how it's used so over here you can see I can pass in the body schema I can pass in query and if I hover over body it has the correct type but if I comment out body now that type doesn't exist and it's of type unknown and so this is the type completion that we were going for whereas essentially only the things that we passed in a schema for are actually accessible from our validated object here and so here I should be able to get access to query and say um your favorite number is and then pass in query.

favorite number and of course we do want that body validation there but again if I comment off the schema here then I get a type error because hey I don't know what query is because you didn't pass a schema for it so this is the kind of type completion that I that I wanted here and now if we try out our point we should get a error because we didn't specify the query parameter so yeah favorite number needs to be specified in the query so if I add the favor number query parameter and set a value on it it validates it and the Handler runs and Returns the message and so that's mainly what I wanted to show you today we Dove a little bit into like typescript generics and also like higher order functions and we' we've got some curried functions going on here um but ultimately I kind of want to just impart the the idea of dream code on to you because if something doesn't exist create it um so if you enjoyed this definitely drop a like subscribe leave a comment if you have any questions about what you saw here and stay tuned because I am going to be releasing a deeper dive video that shows how I built a full

Chapter 13 17:14

go forth and dream

stack app with n in Nitro and H3 so stay tuned for that all right I'll see you in the next one [Music]

Quote it with credit and a link. Quoting Syntax