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

Syntax Video

Build a documented / type-safe API with hono, drizzle, zod, OpenAPI and scalar

Chapter 1 0:00

Intro

have you ever come across API documentation like this where you can see literally every single endpoint documented and you can dive in and see all of the possible response types and see examples of them and then they also have schemas and then you can even go in and test those specific endpoints it actually works and hits the API and you can set the headers and everything else like that well in this video I'm going to show you how to set this up and how to build an API from scratch using hono that fully documents our API using the open API specification so our specific API if you go to/ dooc every single endpoint is documented and you can see all of that here and open API is actually an ecosystem of tools that can use this documentation to create interactive documentation like this or to generate client side libraries or different things like that and so over the past few weeks I've been building apps with hono I specifically have been working with their middleware called Zod open API which essentially allows you to

use Zod to Define all of your schemas and then Define your route contracts and then use those route contracts to get type safety when you're defining your request handlers and then all of that gets turned into fully interactive documentation now we're not just going to talk about open API I'm going to show you all the things I've learned about hono as well and kind of show you some best practices so I'll show you how I set up the app in a nice and clean way and we can create all of these little helpers that basically set up our middlewares and everything else that we need and then whenever we're setting up open API we can do it in a nice scalable way way as well so for instance we can set up all of our route definitions in one spot and then all of our handlers in another spot but everything is still type safe so if we look at our route definitions we can see that they're here and we can also see that I have helpers here that help us Define response types for specific types of status codes and then from there we actually export the types of these route definitions and then we can use them to Define our request handlers so we can Define our

Chapter 2 1:10

Quick Code Tour

handlers in a separate file but we have full type safety that basic Bally knows exactly what we should be responding with for this specific method based on that specific route and then beyond that hono makes it really easy to test these in points because they have this built-in test client that's essentially similar to the hono RPC client that you can use inside of client side code that has fo type safety but it's a really nice testing experience as well and then beyond that we can connect it all up to drizzle so drizzle Zod essentially allows us to Define our tables and then use those table definitions to Define our Zod schema and then we can use these schemas directly inside of our open API definition and so we essentially have a single source of Truth where we can Define our tables we get our schemas we then use those schemas inside of our route definitions and then from there all of the types flow through for when we're defining our Handler so it's actually a beautiful experience and in this video I'm going to show you how we set this up from scratch now like I mentioned I've been working with hono for the past few weeks and essentially I

Chapter 3 2:51

stoker - a hono library

was doing a lot of things that was kind of boilerplate and I was doing them over and over again so I I've created my own Library it's called stoker it lets you stoke the flame cuz hono means flame but basically I have a bunch of built-in utilities and middlewares and various helpers that kind of reduce the boiler plate whenever you're defining your API in this way and I'll show you how this Library works and I'll also show you the source code because if you don't want to use this Library you can write this code directly into your own app and then beyond that I've also created a starter template so I have this hono open API starter that is essentially what we're going to build in this video but it's fully documented it tells you where everything is so you don't have to watch this whole video to basically get the code that I'm going to show you you can start from here and kind of dive in and get your hands dirty with the code directly well like I said I figured out a lot of niceties and best practices for working with hono so even if you don't want to use the starter kit or maybe you've already been working with hono definitely check the timestamps in the description so you can skip ahead to the parts that interest you and that you can potentially adopt into your own hono apps so if that sounds good to you let's

Chapter 4 3:19

hono-open-api-starter

get into it my name is CJ welcome to syntax [Music] now first up let's generate an application so if you head over to hono dodev click on getting started they have a CLI tool that you can run to generate an app so I'll copy this command and then in my terminal run it now I'll give it a name we're going to be building an API for tasks so I'm going to call this the tasks API and now we need to choose where we're going to deploy um now I'm actually just going to choose node.js and I'll show you how we can set this up so that if we want to deploy to somewhere else later on we will be able to do that uh but we're just going to choose nodejs yes for now yes we'll install dependencies I'm using pnpm here we go now let's head into that directory and then open it up with vs code now you can see by default we get a source directory with an index.ts that just has a basic hono app set up inside of here and if we take a look at our package.json it's just using TSX to serve up that app now before we start writing any code I want to get eslint

Chapter 5 4:00

generate hono app

Chapter 6 4:50

eslint / editor settings setup

set up so I have all of my preferred formatting settings and also editor settings and for this I'm actually just going to use ant Fu's ES config so this is a preconfigured config where if you don't want to change any of the settings literally all you have to do is install it and then export it and you don't have to mess around with a bunch of es lint plugins so it's really nice now he provides a CLI tool and this will automatically create the config file and also set up your vs code folder so if we run this command It'll ask us some questions it says there are uncommitted changes that's okay with me and you can use this es config for a lot of different types of projects we're in a backend app so I'm not going to select any framework here and I am going to choose use the formatter now I'm also going to generate that settings. Json and we should be good to go so at this point if we check out our app first of all we have some good default settings here in this file I especially like the one that does automatic fixing of files using ES lint so anytime you save your file it's automatically going to get formatted and linted so that's great and then of course we have our config file so by default super basic it has all the

default settings I have some of my own preferred settings and I just keep this in a GitHub gist so I'm actually just going to overwrite these settings with my preferred settings uh let's go ahead and update dependencies cuz it added those dependencies but it didn't actually install them so if I just do a PN PMI that'll make sure and download those dependencies and now if I head into a source file and then save it it should use all of my default settings now if this doesn't work automatically you might need to reload uh vs code if you press command shift p and then do reload window uh that'll make sure that all of your latest es lint settings are loaded and then it should be able to apply those settings and then lastly we should set up a lint script so if you head over to the package.json we can add a new script here called lint and we'll just run eslint dot so it'll run it on the current directory and now from the command line we can do npm run lint and that'll actually run the linter on all of our files and we can see there already some issues if I want to automatically fix these I can just do npm run lint D- fix and so anything

that's autof fixable it's going to fix for me and then I'll just see any warnings or errors that are left behind and right now we do have a console statement now I like to have fix as a separate command so I'll add that as a separate command here I can do lint colon fix and this will just be mpm run lint D- fix and so now if I ever want to fix all of my files automatically I have a separate command I can run now one thing I like to do for the typescript setup is make it so that I can import with an alias so for example if I'm importing anything from Source SL lib or Source routes instead of needing relative pass I can do at slash lib or at slash routes or whatever the folder may be and so here in my ts config I can add add a section called paths and then I want to map at SL star to anything in the source directory SL star and so now I have a nice import and that way I don't have to do relative Imports next up we're going to install hono Zod open API so once you install this package anytime you need to create a hono app you'll be using this dependency instead so we're going to go ahead and set it up

Chapter 7 7:11

typescript import alias

Chapter 8 7:41

install @hono/zod-openapi

now if you head to their repo they have an install command that you can run now from here I can use hono Zod open API to actually create an app so if you see in there Docs notice we import open API hono and then we use that to create an app and it is just a wrapper around hono so you can uh use it directly and your app will still work in exactly the same way but the first thing I'd like to do is extract out this app into its own file and so that way it's separate from all of the node specific stuff and so for this we'll actually create a new file called app. TS and this is where we're going to Define our app so I'm going to pull out the code that actually defines the app paste it here inside of app. TS and then export it as the default export now from here I just need to import this exported app inside of index.ts so if I head over here and then import app then save it now it should be good to go so essentially what's going to happen is all of our codes that we write for hono and open API are going to

Chapter 9 8:10

extract hono app to own file

be with this file and then whenever we need to run it locally we're going to be using this file but if we decide to deploy to versel or cloudflare or anywhere else we can actually create an updated entry point that uses a different serve and then passes in the same application and now before we start the server up I'll just update this log here uh I'm just going to set this to http localhost colon and then the port this will make it so that I can actually click the URL from the console and then the other thing we can do is we can actually disable this linter warning because I do want to allow a console log right here so if I do command period I can say disable no console for this line and now I don't have a linter error anymore uh but from here we can actually start the app up so if you look back at our package.json we have this Dev script which watches index.ts so from the command line if we run mpm run Dev should start up our hono app and it'll start listening and now if I head over to Local Host 3000 we see that index route now one of the first things I like to do when setting up a hono API is make sure that I have a not found Handler

Chapter 10 9:43

notFound handler

that responds with Json in a consistent way and then also an error Handler so by default there is a built-in not found Handler so if I try to go somewhere that isn't found it still responds with a 404 but since this is going to be a pure Json API I want to make sure that this responds with Json so if you look in the hono Dos there is a not found method on the app and then you can pass in a custom Handler now the way that I set this up is exactly the same every time and I don't want to have to do this over and over again in every app so I actually wrote a custom package it's called stoker and as we set up this hono app you're going to see me use some of the built-in methods and utilities that I have here and the first one is not found so you can just import it from stoker and then pass it in to not found now all of the source code for Stoker is on GitHub and so if you don't want to add another dependency to your app feel free to just go copy paste so if you look in the source directory I have a middleware folder and then I have a few of these that we're going to be using and if you look at the not found Handler essentially it just responds with an object where the message includes the path that was not found the other thing

that my library also includes are status code constants and status code phrases so you can see here that it's using the status code not found which is actually 404 but I don't want to hardcode numbers all over my codebase so the status code helpers are really useful as well so let's install the stoker package so if I do npmi stoker we get it and now I can use it and so right here if I say app.

not found and then search for not found you can see that Auto Import there from stoker and now with that setup if we try to go to something that isn't found like banana it's always going to respond with Json data and so this is great because your API clients don't have to worry about figuring out what kind of data your API is responding with in this case it's always going to respond with Json the other thing we want to do is set up an error Handler so we can have that consistent Json response so built into hono is another method called on error you can pass in an error Handler and then customize the error response and so to see this in action let's actually create an inpoint that always throws an error so if we do a get on slash error all this is going to do is just throw an error says oh no but let's see what happens if you don't have this on error Handler set up so by default if we go to SL error you'll see that it just responds with a generic 500 internal server error uh but again we want to have consistent responses so we can write a custom error Handler that always

Chapter 11 11:30

onError handler

responds with Json now again I have a custom middleware inside of stoker that's called the on error and you can just pass it in but if you want to take a look at the source code essentially what it does is it checks to see if any code before it has set a status code and if it has that's what it's going to set the status code AS so if for whatever reason you had set a custom status code here like c. status and maybe you did like 422 or something like that this piece of code right here will take that into account and then actually use that status code in the response but aside from that it's going to grab that error object and include the message and then if no to EnV is not set to production it'll show the stack Trace so let's add that error Handler now so if I do app.on error and then pass in on error which comes from stoker middlewares now if we hit that/ error route it's going to respond with Json and then include the stack trace and so this is nice because if for whatever reason you forget to do like your own error handling this will always catch it and it will respond in a

Chapter 12 13:08

logger middleware

consistent way now next I want to set up some request logging so you can see by default hono does not log anything whenever you see incoming commands and they actually have a built-in request logger so if you look in their docs then search for logger this one is just builtin and it's pretty basic but let's go ahead and set it up so we can see how it looks so if I just do app.use and then pass in logger which comes from hono logger now if we take a look at the command line anytime a request comes in we're going to see it logged out here so if I make this request and then look back at the command line You'll see that a request came in for error and then a response was sent back with error code 422 now this Handler is perfectly fine if you just want to see the basics of incoming and outgoing requests but in production you typically want to see a lot more information about the request so it's easier to debug and the standard for that is to use some kind of structured logging and Pino is used heavily in the world of nodejs so this is a generic structured logger so you

Chapter 13 13:52

structured logging with pino and hono-pino

can just pass in logs and by default it logs as Json and there are various tools that can actually consume these logs and you can display them visually so it's a great way to add logging to your app now they have a bunch of uh helpers for all of the other common web Frameworks there isn't an official one for hono yet but I did find one that I like so if you search mpm for hono Pino you'll see two different options um I tried them both out and like this one just because it logs more of the information about the request and it's a bit more customizable so we're going to install hono Pino and also Pino into our app so I'll run that install and now we can set it up so I like to create a folder called middle Wares and anytime I'm creating a custom middleware or customizing an existing middleware I'll add it to this folder so let's add a folder called middlewares and inside of there I'm going to create a file called Pino logger TS now to set it up they actually don't have much documentation but I did the hard work for you I took a look at the source code they they provide this configuration interface so you can see all of the

things that are available and I'll show you the main things that we're going to want to customize so from this file we're going to export a function called penino logger and it will just return logger from honoo we'll have to manually import it if we import logger from Hop Pino that grabs the logger and let's take a look and see what we get by default so I'll import this logger over here in my appts so I can get rid of that logger there and then instead we'll bring in Pino logger and now let's see what we get so our app is waiting for incoming requests and now if I make a request here and we look at the logs we can see that it is actually logging a whole lot more information and so it actually logs these as Json objects um but when I'm in development I want to be able to read this a little bit better and so there are a bunch of plugins in the penino ecosystem including one that's called Pino pretty and it'll pretty print the logs so I'm going to install that plugin and I'll show you how we can figure it with this middleware so here it is on mpm we can just npm install Pino Das pretty so

Chapter 14 15:46

hono-pino pretty logs and customization

we'll do that now that we have the plug-in we will use it and the way that it works is whenever you create a Pino instance you can pass in an instance of pretty which is what we need to do but after taking a look at the examples in configuration interface here on hono Pino um you can actually pass in an object of options and one of those options is penino and you can pass in a Pino instance so right here I'm going to pass in a penino instance and so I'll just import this from penino like that and so now it should still work so if you take a look back at our logs and then try making a request to our app it should work just fine but now we can actually start to customize penino and the thing that we want to do is pass in pretty so if we pull pretty in from penino pretty now let's take a look at the logs so if I make a request to my app it's nice and readable and it has like nice colors and everything else too um and so this is really great especially when I'm in development so I can see that there was an incoming

request I can see what the headers were I can see what the response status code was so this is awesome now another thing I want to do with the logger is customize the request ID so whenever you're looking at these logs when something goes wrong uh you want these to be very unique and you can see by default it just starts counting up and so like if you're in a serverless environment or if the server ever goes up and goes down these request IDs are going to reset so we want these to be globally unique and for that we can actually pass in some options to the logger here so there's some HTTP options and there's an option for request ID where we can pass in a custom function and what I'll do here is just use the crypto API so crypto is built in to the web standards and we can then say random uu ID and so now every incoming request is going to have a request ID that is a random uyu ID and so now let's take a look if I make a request to my app we can see that these request IDs are now uyu IDs and what's nice about this is now now if I have like distributed deployments or serverless or whatever

else all of these request IDs are going to be unique regardless of where those requests were coming in now another cool thing about this Pino logger is you can actually access it inside of your request handlers and then log using structured logs and using the penino logger so for instance if I'm here inside of let's say like this request and here I can actually access the Pino logger instance so if I do C.V var.

logger which is the default name dot I can then access any Pino logger method so if you look at Pino they have Trace debug info warn error fatal these are all different levels of logging and you can use these methods now that you have access to the logger so we get a type error right now we're going to fix that type error soon but for instance I can say info and then say wow log here and now whenever this inpoint gets hit we're actually going to see this log in the output of the Pino logs so if I for instance make a request against here again now we can see the info log happens right there and so this is really nice because instead of just having console logs everywhere you can actually have these structured logs and so if we actually turn off pretty printing you can see what these logs are going to look like whenever we're loading these into some external tool so if I turn off pretty Printing and then make this request here we can actually see that that log isn't just the text it also has the time that it was logged the process ID and other relevant information so this is the idea with structured logging is that now some other tool is able to consume these and

it can group them by time and and various things like that now I don't want to have pretty printing on all the time and so one thing I want want to do is only enable pretty printing if we're not in production so to do that we can just access it from process. EnV so here I can say process. env. node EnV so this is the standard EnV that will say what your environment is and typically when you're deployed to like versell or other environments node EnV is going to be set to production so here we can say if node EnV is equal to production then don't do anything we're just going to say undefined right here otherwise we're going to invoke the pretty instance we are getting a linter error about process studying we're going to fix that soon uh but check it out if I start up my app but I say node EnV is uh production now now by default those logs are not going to be pretty printed and this is what you want in production because you want to be able to consume these using some sort of uh log aggregation tool but if I'm not running in production then we should see the pretty printed log so if

I make this request here now we see the pretty printed logs now to fix this type error here we can actually set up our hono app so that it knows about these other variables that have been set using some custom typescript types so if you look in the hono documentation under generics you can see that we can pass in a generic type to the hono instance and tell it what variables are available now if you look in hono Pino it's a bit hard to find but if you look in their source code and then take a look at the types they show that they're actually setting logger to be P logger inside of the variables property here so we can set that up so what I'll do now is create a custom type let's call it app bindings and inside of here we have a variables property now you can actually set all kinds of custom variables but in this case we're just going to let it know about that Pino logger and so right here I'm going to say logger is an instance of Pino logger and I'll import that type from hono Pino and so now if I use this app bindings type when I access logger it's going to be of type Pino

Chapter 15 20:23

typesafe hono AppBindings

logger and the way that we use this type is by passing it in as a generic here whenever we create the app instance so if I pass in my app bindings now can see that that type error goes away and now we can see that I get full type completion I can see all of the various methods that I have access to and so now it's a bit nicer to use cuz I actually know what methods are available and and I'm not getting a a type error now you can see in hono Pino it's actually possible to customize the name of the logger like you could call it my logger or you could create multiple middlewares that all have a different logger name for my application we're going to use the same logger everywhere so I don't need to customize the context key here I'm just going to use the default name of logger now one more setting I want to enable here for the Pino logger is to set the log level so Pino actually accepts some options and inside of those options you have the option for level and this can be any one of these and by default it's set to info and this is nice because by default if you have debug logs they're not automatically going to show up unless you specifically

Chapter 16 21:56

pino log level setting

set the level to debug and and basically debug is the lowest and it goes debug info warn error fat fatal and so basically depending on the level that set all the the the levels above that are always going to get logged out and so essentially whenever I'm in development I want to see those debug logs and for this I'm just going to pull the log level from process. EnV so I'm going to say process. env. log level you can set this to whatever you want uh but essentially I'm going to have an environment variable called log level and if it's not set then we're going to just have the default of info and so now whenever log level is set it'll use that specific log level and so for instance inside of this if I were to do a debug log and so now that's a debug log and by default I don't have an EnV set up right now so the level is just going to be info and so if we make another request to our app and we look at the logs I'm not going to see that debug log but if I start up the app and log level is set to something like debug now I will see it so if I make a request to my app you're

going to see that debug log logged out and so this is nice because you can leave these logs in your code and in production you won't have like a super busy output but if for whatever reason something is going wrong you can't figure it out you can enable these debug logs and then you'll be able to see those logs to try and figure out what's going on even if the code is running in production now at this point I actually want to set up an environment variable file so let's do just that so first I'll create a file we'll call ITV and in here I'm going to set the node EnV to development and I'm also going to set the log level to debug and also we'll set up the port so let's put this on a different port I'm going to put on like 99.99 um and I I actually want to use this this port variable as well so if we look in our index.ts right now it's just hard-coded as 3000 but we could also pull in from process. env. Port and if that's not set up then use port 3000 um and in this case I'm just going to parse it as a number because the serve function here expects that to be a number so I'm using environment

Chapter 17 23:35

dotenv setup

variables in several places right we've got the port set up here and then we're using what the log level in the node EnV inside of here uh let's actually get these EnV variables loaded in and so for that I'm going to use a package called EnV so I'm going to install EnV the other thing is sometimes I like to use environment variables that require expansion like basically have environment variables embedded and referenced inside of other environment variables and for that we actually need a secondary package now called EnV expand and so I'll install those two things and then we'll set it up and so I'll just set this up inside of app. TS right now we're going to change where it is in a second I just want to make sure that it's working but if we import config from EnV we can that and then we also need to call expand so I'll import expand from EnV expand like that and then we can pass config into expand like so and now whenever the app starts up this will automatically read in that EMV file that I have specified here in the

folder so it's going to pull in the port number the log level and everything else and so now if I kill the app actually you can see it restarted it's actually using uh Port 9999 because it read in that and v file and now it's actually using those values now at this point I want to use these environment variables in a typesafe way you can already see that I have this lter error and essentially I have a lter error set up that says you should not use process.

Chapter 18 25:30

typesafe env with zod

EnV anywhere in your application and the reason that I have this rule is because every app that requires using environment variables I set up a typesafe EnV and the only way to get access to those environment variables is to access it directly from that typ safe EnV so that's what we're going to set up now we're basically going to set up a typescript type that will give us access to these variables and will make it so the app won't even start up if these required variables are not set and to do that we're going to use Zod so Zod is a schema validator we're already going to be using Zod for validating all of the schemas of all of our endpoints so we can just use Zod to validate our EnV as well so the way I like to set this up is to create a file called env. TS and then inside of here we can import Z from Zod and we should already have Zod installed because earlier whenever we installed hono Zod open API it included Zod as a dependency but if you didn't do that make sure that you install Zod and now I can create my EnV schema and this will be an object and essentially I want to

specify all of those environment variables that I want to make sure are set or I can set up some default values so inside of here I'm going to say that node EnV is a string and it's going to default to development so if someone didn't set it it'll just have a default value of development and then Port is a number so we can actually do z. co.

number and so this will actually read it in as a string but then turn it into a number so we can use it as a number which it is and we will default that to 9999 as well and then lastly we'll also set up log level and for this we can use z. enum and we'll pass in the type level and so this type comes from Pino I'm going to have to import it manually so import level from Pino like that now because level is actually a type we can't pass it directly in but I did this so that way we can go to its reference so if I say go to definition we can see where it's defined and then here we can see that Union and we're actually going to have to pass this in directly so here I can pass in an array and then for each of these we'll just change it to commas like so and so this is duplication CU we had to pull it out of the Poo library but now I should get good type completion if I'm ever writing code to specifically check that log level there now the other thing I'll do is I'll actually move ourv code into this file so it's all handled in the same spot so

basically I want to grab config and expand and throw these in here and then I also want to grab this and throw this in here so now we'll read in the EnV we'll Define our schema and then we actually want to parse it so I'm going to create a variable called EnV and I'm going to set this equal to EnV schema.

parse and I'm actually going to pass in process.env and so this is the only place in my entire application where I'll access process. V otherwise I'm going to be using this type directly CU you can see now if I hover over this it has a very specific type and this is what I'll use anywhere where I need myv so I'll save this um and I will disable this lter error here so we are allowed to use process EnV right here but we don't want to use it anywhere else um and then I'm going to export this as the default option so export default EnV just like this and now let's search our codebase for process. EnV and get rid of all those instances and make sure that we're using our typ safe EnV so over here here when I'm using process. env.

port instead I want to use env. port and I'll import that in from EnV and now I don't need to parse it I also don't need to have a default option here because I'm actually setting a default option in my schema okay so that file is good to go another place I was doing it was here inside of the Pino logger so here I actually want to access EnV like so and we'll import that in from EnV so now I'm accessing my EnV in a type safe way but let's actually see what happens if one of these isn't defined so right now log level does not have a default value and let's actually remove it from our EnV so if we go head over to our EnV and then remove log level let kill the app and start it back up you can see that it actually spits out an airor so because we're parsing that EnV whenever the app starts up this actually kills the app and then logs out this this Zod error here um but we can clean that up a little bit so inside of our EnV file first I'm actually going to get the type of our EnV schema and you can do that with z. infer so I'm going to export a

type called EnV we're going to set that equal to z. infer and pass in type of EnV schema and so this is a built-in way inside of Zod where it allows us to actually get that type out and so I can just use that type directly now the other thing I'll do is Define the variable first we'll just say let EnV which is of type EnV and then we'll overwrite it here and the reason I want to do this is because this can throw an error but if it doesn't throw an error then that means EnV is going to be of the right type so we should be good there um I am going to have to disable some lter errors so we're not going to do mutable exports we're also going to allow a redeclaration and so now the exported type is of type EnV now the other thing I'll do is wrap this inside of a tri catch because if it throws we can actually log the error out in a nice way so we'll catch this I'm going to call this e and then I know that this is a type of Zod error so I can say as Zod error which comes from Zod and there's a

built-in method on the Zod error called flattened and so this gives us a nice readable error and we're just going to log that out so above this I'll just do console. error and let's add a nice little X emoji that says uh invalid EnV and then we'll also log out the errors here so I'll pass error. flatten into that um and then lastly we'll just exit the process so here I'm just going to say process. exit and if we give an exit code of one then that means there was an error and so now the app will not start up and we're going to get a nice error logged out here and so now if I try to start up the app you'll see that it says invalid EnV and it tells us specifically what the issue was now in this case um I just want field errors so I'm going to update the log so we'll say flatten and then grab those field errors and now um it tells us explicitly what we're missing and so if I head back over to my EnV and I add a log level let's say I set it to debug now I can save that and if I restart the app should actually

start up and so this this is a nice way to do things because now if any of those required environment variables are missing the application won't even start up and so this makes it much easier to debug even in production if you're missing an EnV because literally the app won't start and you'll see in your logs exactly which environment variables are missing and from this point anytime I need another environment variable like a database URL or an off secret or anything else like that I'm going to add it specifically to my schema here and that way it'll ensure that we're using it in a type safe way now another middleware I want to add is to up a fav icon so you can see that by default anytime a a web browser is making a request to our server it always is making this request to SL favicon and our server is responding with a 404 because that thing does not exist uh but inside of my stoker package I have a middleware you can use that's called serve Emoji favicon so you can just pass in an emoji and now anytime a request comes in for SL favicon.ico it's actually going to respond with an SVG that has that emoji inside of it so I'll

Chapter 19 32:25

serveEmojiFavicon middleware

set that up right here before the Pino logger if I say app.use I can say serve Emoji favicon bring that in from stoker middlewares and then pass in a specific emoji and since this is a task list API I'm going to pull in this pencil and paper emoji there and so now that I have this middleware anytime a request comes in for slfac con. I it's automatically going to respond with that specific Emoji so if I go directly there faac con. I you'll see it responds with a giant emoji but now whenever I visit the site inside of my browser it actually has that emoji set in the URL bar as well now at this point we're looking pretty good we've got all of our default middlewares our eror handlers we've got all of our our custom types set up uh but now let's just clean things up a little bit before we start adding all of our nested routes and one thing I want to do is take all the logic that sets up our app like adding these middle Wares and not found and on air handler and put that into a reusable function because later on whenever we're testing our nested routes this will come in handy so

Chapter 20 33:33

clean up app creation

that way we actually have our logger mle Weare and everything else when we're testing our routes in isolation so here in the source folder I'm going to create another folder called lib so this is just short for library and inside of there I'm going to create a file called create app. TS now we're essentially just going to grab everything from app. TS right now and put this in here but we're going to wrap it into a function so I don't need these handlers right I don't want the slash route or that example error route I really just want this right the the main setup here and so I'm going to put this into a function called create app and then we'll return that app from here and this is what I will export as default from this specific file and then here to update this import we can just use that import Alias that we set up earlier so if I just do at slash it knows to import it from The Source directory in the middlewares folder now if I head back over to app. we can remove all of the stuff that we set up here so I'll remove that I'll remove all of this we can get rid of this type all of those unused Imports and at this point I can just say

create app like so and use the import Alias like that sweet and so now I have a nice reusable function that actually includes all of my middlewares and everything else and like I said we're going to use this later on whenever we're doing our testing now one more thing I want to move around are these app bindings because I'm going to potentially use this in multiple places so I'm just going to move this to a file called types so I'll create a types. TS and then move these app bindings into that file and then anytime I need them I'll import them from here so I'll export this from App bindings and then import from honoo so now over here we'll need to import this from types like so and then I can remove any unused Imports now one setting I like to enable for my hono apps is to disable strict mode so if you look in the docs by default hono differentiates between SL hello and SL hello slash and for the apps that I build I don't ever want to differentiate those these should be the exact same path and so for instance inside of our

Chapter 21 35:36

hono strict mode

app if we go to slash error that works but if we go to SL error slash that actually returns a not found and that's because of that trailing slash so whenever I set up the hono app I'm actually going to pass in strict as false so we can do that right here and now whenever I request error slash that will resolve to the actual error route like I expected it to now let's actually set up open API with our application so I'm going to remove all of these example routes cuz we don't need those and I'm going to create a function called configure open API and so what I want to do in this function is I want to be able to pass in my hono app and then add the slash do inpoint and so this will actually respond with the open API specification at SL do and then after that we'll actually set up our documentation page that uses those docs but we're going to do all of that inside of this function so here I want to take in the app now to get the type of the app we can actually use the same type that we use to instantiate the app but I'm going to Define this inside of types so that it's reusable because we're

Chapter 22 36:16

configure openapi doc endpoint

going to use it in some other places as well so here I'm going to export a type we're going to call this app open API and we're going to set it equal to this specific type here and so now anywhere I need to use this type which is specifically an open API hono instance that is using these specific bindings I can just use my type here which is called app open API and so now that I have that type we'll use it right here so this will be a type of app open API and then from there we can call our documentation function so we'll grab this and call it there I'll update the title to just be the tasks API now for the version I want this to stay in sync with the version of my mpm repo so first we'll actually Define the version in our package.json so this is a standard field and we'll just keep this up to date anytime we add new features or whatever else so I'm going to set this to 1.0.0 and now inside of this file I'm actually just going to import in that package.json directly and then use that version field so that way anytime we bump the version this documentation endpoint will always have the latest version specified in our package.json so

I'm going to import our package Json from go up a few directories and then grab that package.json and then right here I can just say package.json dovers awesome now I need to use this function after creating the application so if we head back over to our app. TS after creating the app we want to call configure open API and then pass in the app like that and so now the app gets instantiated adds all of our middlewares and then we set up our documentation inpoint here and so if we head to the browser and go to SL do we should see our specification and right now we don't have any endpoints so it's just a blank default specification but you can see it's bringing in that version number from our package.json and now as we add any routes that are documented those will get listed here as well now to see this documentation in action let's actually create an inpoint so I'm going to create a folder called routes and inside of that I'm just going to create a root route we're going to call this index. route. TS and this file is actually going to export a hono API

Chapter 23 38:36

createRouter helper

instance that has a specific documented route so the first thing we need to do is create an open API hono instance now if you remember back in our create app function we do have this create app method but I want to create a hono instance that doesn't have all of these middlewares it's basically stand alone and then it's going to be mounted on top of this app so I'm actually going to Define another function that's called create router and this will just return this so anytime I need a new router it's going to have the correct typings and I can just call this function and we can reuse this function inside of here just say create router like that but now I can't have two default exports so I'll just remove default From Here and Now this file exports two things it exports create app as default and then it also exports this create router function that we can use and so with that now if we head to this index. route file I can create my router by saying uh create router and then I'll export this as default like so but now I can actually create an inpoint so if we look in the Zod open API documentation you can see

Chapter 24 39:33

create index route

that they have this built-in method called open API and on that we specify our route definition so this is actually what will be documented whenever we hit the slash do inpoint and then we also pass in our Handler or our implementation so let's do just that right here I'm going to say. open API and then I'm going to use the create route function which is built into hos.

open API and then I'll pass in my options here in this case the method is just going to be get the path is just going to be slash and then we can document how this inpoint is going to respond so here we can add responses and then responses is an object where the keys are the http P status code so for instance for a successful response the HTTP status code is going to be 200 and then we can specify how this inpoint is going to respond when it's a 200 status code and we can pass in our options here we can set the content and then within the content we'll say that this is going to be application Json and then within that we can specify our schema and the schema is just a Zod validator that specifies how this thing is going to respond so let's actually just create a super simple uh object schema with a message property so I'll pull in Z and we'll do Z doob I'll make sure that I pull that in from hono zad open API and then I can pass in my options so now in this case I'll say that it has a message property which is going to be a string uh and then lastly I need to describe it so we'll add a description property and

I'll just say this the tasks API index so this describes my inpoint we're saying what the method is going to be what the path is going to be and how we're going to respond now we need to actually implement it and so the second argument into open API is the Handler that will adhere to this specific contract so right here we can pass in our Handler so this is just a plain old hono Handler like any other Handler that we Define except it's going to be typed to make sure that we respond in this way and so we get the context and then we can write our implementation and so when we get into more complex routes we'll be querying our databases we'll be doing everything required for a specific route in this case we literally just need to respond with an object that has a message property so I'm just going to return c. Json pass this in and check this out if I do control space we get type completion and we can see here that it says hey there should be a message property and that's because the types are flowing through right I Define my contract here which says we're going to be responding with an object has a message property and then down here we specifically get that type completion to

say hey you need a message property so here I'm going to just say that this is the tasks API and so basically every single route that we Define within our application we're going to do in this way we're going to document it and then we're going to implement it uh and what's nice about this is if I respond like with the wrong status code like 401 I get a type error so here you'll get a type error that says hey you only said you were going to be responding with a 200 status code so you need to document that and so if I did want to respond with other types of status codes I could go in here and say okay well sometimes you might get a 401 response and then this is what the response would look like uh but for now this should be good enough and we have our root endpoint and so now I need to mount this specific endpoint onto our main application and the way that I'll do that is just right here inside of app. TS so I'm going to create a variable called routes and this is just going to be an array that has all of the routers that get defined inside of this routes folder and so right here I can pull in that index route and then I'm just going to have to um import it manually so we're going to

Chapter 25 42:42

mount index router on application

import index from atrout index. Route like that uh and while I'm at it I can update this to use my Alias import as well okay so I have this array of routes and now I can actually iterate over it so after configuring open API with the Basse application from there I can mount each of my individual sub routers so here we're just going to do routes. for each and for each route we're then going to say app. route specify the root path and then pass that specific route in like so and so this should do it this should actually give us a route at the index and also this should show up inside of our documentation so if we refresh our documentation we should see that we now have this inpoint documented that says if you go to slash we will respond with a git route and the possible responses are potentially an object that has a message property that is of typ string and so if we go to the index route we get back that specific object now next up I actually want to set up some interactive documentation and this

Chapter 26 44:02

open api overview

specification is great because it literally describes all of my endpoints but this is an open API specification so this is a a set standard and if you describe your apis in this way there's a whole ecosystem of tools that can create like interactive documentation or automatically create client libraries and like pretty much any programming language so this is really awesome and one of the things we're going to set up is interactive documentation now you probably have seen a UI that looks like this before this is Swagger UI and it's based on top of the open API specification so if I actually just grab my spec here copy that Json I can go to this Swagger editor and paste it in uh I'm not going to convert it to yl but then you can see that we get interactive documentation over on the right hand side and we can see the specific schema we can see our inp points it even gives us the ability to try it out this won't work because we haven't set like the root URL uh but this is one of the Great great things about having the specification now Swagger UI is awesome but there's this newer tool called scaler and it is really slick so they do have like a paid hosted platform but the

Chapter 27 45:00

scalar documentation setup

actual scaler docs that you can add to your application are completely open source and you can just host it yourself and so if we take our specification and paste it into their like interactive editor here this is what we're going to be able to get we get this documentation that will specify all of our endpoints it will then show all of the documented responses and schemas and then we can also click test and this is very similar to like Postman or thunder client or anything you've used before for testing apis where you can specify headers you can specify the body like if it's a post request and all of this will just be right inside of the web browser and the way you set this up is actually just with an HTML file so you can actually have an HTML file pull in the library from a CDN and then point it at your specific documentation endpoint but we don't have to do it manually so there is a package called scaler hono API reference and we can just add this directly to our app and it'll instantly set up that documentation inpoint so let's do it I'm going to install this Library like so and then we're going to grab this and inside of our configure

open API function we can call it so I'll call it right after we set up SL dooc we'll do this here and then I'll import API reference from there now you can see here they're specifying the URL this just needs to point to where your documentation lives and in our case it lives at/ doc so we'll just update this to be/ do great and just like that we should have some interactive documentation ready to go at slash reference so if we head back over to our API and go to SL reference it breaks okay I I think I know what I forgot so we've been building our app this whole time and we're actually still in commonjs mode so if we take a look at our package.json we don't have type module set and we should because we're using uh ecmascript modules we're using types scripts we actually do need to set type to module if we set that and then restart it should be good to go okay so we should have set that up earlier but essentially we want to make sure that importing everything as ecmascript modules because that's the code that we're writing okay but now that I have that if I head to SL reference here we

Chapter 28 46:30

package.json type module

Chapter 29 47:00

scalar customization

go we have our fully documented endpoints here so you can see I can see all of the routes on the left I can click on them and then I can click on test and this then allows me to change the headers the body Etc and we can actually test out our API so now every inpoint I create in this way is going to automatically get listed here and then I can test it in an interactive way now the library also makes some options available like the theme so they have several different themes that you can use I actually like the theme that is called Kepler so I'm going to set that here I'm going to set theme to Kepler and then with that set like the look of that a whole lot better so that's awesome and you can try out all the themes pick the one that you like and there are actually more options available so if you head over to the main scaler repo they have a section under themes and a section for configuration and this shows more stuff that we can customize so specifically if you look at layout there are two layouts available there's the modern layout which is two columns and then there's is the classic layout I actually prefer the classic layout so let me show you what that looks like if we set layout to Classic and then head back over to the

docs now it just shows everything top down and this is just my preference but I do like to see all of my in points here and once you have a lot of endpoints even though it's in a single column you can still use the search box here to filter it down so yeah I like the classic layout choose whichever one you want uh now the other thing is we can set the default client Library so this is one of the cool things about this test client here is whenever you look at the docs here depending on what you have your test client as it'll show the actual code for that so if I choose nodejs it'll show me how I might make this request in node or in python or in JavaScript fetch so whatever your client language is going to be you can actually set that as the default and that's what I'm going to do next so if you look in the docs and go to the configuration section they have a thing called default HTTP client and here you can choose the target key and the client key so I'm going to do just that I'm going to set the target key as JavaScript and then the client key as Fetch and so then anytime I go to my docs it'll always show me the Fetch and JavaScript examples instead of of curl uh so here we can say the default HTTP client and then we need to specify the target key

which will be JavaScript and the client key which will be Fetch and so with that now anytime I go to this page here it's always going to have JavaScript fetch set as the default and so when I look at the documentation for any of my endpoints I'm always going to see the fetch example here so this looks good to me uh now I want to specify some more options whenever setting up our open API application instance so you can see in the Zod open API docs whenever you create an instance you can actually pass in the default hook and so essentially if there's a validation error in any one of your endpoints we can handle it in a common place because without this default hook you actually pass in a third argument whenever you're specifying an open API inpoint but every single one of my endpoints is going to be using Zod validators so I'm going to respond in a consistent way and then I don't have a bunch of duplicate code for every single route Handler so whenever we create our instance we need to pass in that default hook so I actually have a default hook speci speci ified in the stoker Library if you want to use this default hook so if you look in the repo go into open API and then there's a file

Chapter 30 49:21

OpenAPIHono defaultHook

called default hook essentially if the result was not a success meaning there was a validation error then it's going to respond with success false and then include the full Zod error so I like including the Zod errors in my API responses because they're pretty easy to iterate over like in client side code and then like potentially individually show any errors that pop up uh so this basically Returns the full Zod error and responds with a 422 status code so in my app whenever I create the app we're actually going to pass that default hook in so right here I can say the default hook and then specify now of course you don't have to use the one from stoker you can specify your own default hook but we can just actually pull that directly in from stoker and so now if there's any sort of validation error in any one of my endpoints that I defined it's always going to respond in the exact same way now before we start defining some of our other in points I do want to show you some of the other helpers that I have built into my stoker Library CU I'm going to be using them as we build the application and so one of these helpers is called Json content and

Chapter 31 50:48

stoker openapi helpers

so when you're defining these open API endpoints especially if you're defining a pure Json API you do this over and over again every single one of your responses you set the content to application Json you pass in the schema and you pass in a description and so instead of having to do this in every single spot this helper basically just allows you to pass in the schema and the description and then returns an object that looks like that so we can use this right here so we can grab our schema here and then just set this as Json content and so that gets pulled in from our helpers and then we can pass in the schema and then after that pass in the description and then get rid of all this boiler plate and so now this cleans things up a bit so anywhere else where I need to respond with Json content I don't have to constantly specify application Json I can just use that helper which comes from stoker the other helper that I like to use is for HTTP status codes so built into stoker are the status codes essentially these come directly from the http status codes Library which is tried and true it has

over 2 million weekly downloads this is used in most production backend apis that are built with JavaScript or typescript uh but the type system in Zod hono API doesn't work very well with it because it exports enums so my library exports the same things but just as const so they can be used with the hono Zod open API type system and the hono built-in like status code type so for instance we can pull in status codes so you can say import Star as HTTP stat status codes from stoker HTTP status codes and then we can use it and we can actually use a computed property here so instead of using 200 we can just say brackets statusc codes. okay and now this is a little bit more readable so we can specifically see what the status code name is and how it's going to respond uh and you can use those status codes whenever you're doing Json as well so we could respond with okay right here and the types still work right so if I for whatever reason responded with like 401 you're going to get a type error because it needs to specifically match

any of the status codes that you specify here and the type system still works so that you can specify a number Standalone but in my entire code base if I'm using a status code I like to use specifically these HTTP status code uh cons now another built-in helper inside of stoker is actually called create message object schema I find myself doing this over and over again like I might have some inpoint that just responds with an object that has a message property and instead of redefining this schema in every single spot this helper just basically creat Crees that and you can pass in the uh example message that gets created there so right here instead of defining an object with a message property schema I can just say create message object schema pass in the example string in this case it'll just be tasks API and now I don't have to Define that schema everywhere and so I found I found myself redefining that schema over and over again which is why I created that helper uh but now if we look at the documentation we should see the example actually includes that examp

example text that we passed in and then whenever we test it out we can see that it responds in the right way now one more thing to note whenever you're defining these in points is you can actually set up tags and tags are how you group things together and so in create route you can pass in a tags array and here you can specify any group that it should appear in inside of the documentation and in this case I'm just going to call it the index because this is just like the index route but now that I've added that tag instead of saying default it specifically is going to be grouped to the index route and so now every single router that I Define if I want those routes to be grouped together inside the documentation I'll just include that exact same tag and then the docs will actually group those together so at this point we're all set up right we've got our middle wees we've got our error handlers we've got our docs being automatically generated we've got our reference UI that we could use now we can actually start writing application code and so essentially what I like to do is any new route that I Define I like to give it its own folder inside of the routes folder and so we're specifically going to be building a tasks API so I'm going to create a

Chapter 32 54:01

group route definitions with tags

Chapter 33 54:34

tasks router setup

folder called called tasks and inside of there I need to create the router so we'll create a file inside of here called tasks. index.ts we're going to create ourselves a router and then we're going to export that as default and then we need to be sure to register it so if we head over to app we're going to add it to this list of routes we're going to add tasks here and tasks comes from SL routes SL tasks SL tasks. index and because it exists in this array it's automatically going to be mounted now it's a completely empty router at this point like if we refresh our docs we're not going to get any extra end points because we haven't created any yet but let's do just that so the way I like to do this when I have a lot of endpoints is actually Define my routes in a separate file so I'm going to create a file here called tasks. routes. TS and this is going to export all of the route definitions that are essentially the contracts that we'll Implement inside of the handlers and so for this task API the root at task is going to be a list request so this is going to be a request for all of the tasks within the system

Chapter 34 55:32

tasks list route

so I'm going to create a definition that describes that we will respond with an array of tasks so let's create our list Handler and we're going to use create route which comes from hono out open API and then we'll pass in all of our settings here we'll specify the path as/ tasks and then the method is going to be get and then we can specify our responses and so in here we'll Define the response for the 200 status code uh and in this case I'm just going to import again from that HTTP status codes helper from Stoker CTB status codes and then we can use the 200 status code so a successful response is just going to be a Json array again we're going to use that helper method Json content and then we need to pass in the schema now we are going to set up a database and we'll actually be able to use a Zod schema that directly corresponds to a table from our database but for now just to see this working I'm going to Define kind of just like a dummy schema and then we'll set up the database and we'll get like the real schema in here uh but in this case I'm just going to say that

this responds with an array um and I can can grab Z from hono open API and then I can say that it's going to respond with an array of objects and then because these are tasks let's say each one has a name so let's just do a z. string and then it has a done property which is like z.b like I said we're just hardcoding this for now we are going to set up a real database and then pull the schema from there but this should be good so that way we can Implement our request Handler uh and then we also need to pass in a description so this is the list of tasks like so so now that I have the route definition I want to define the actual Handler that's going to implement the logic to actually respond with this array of tasks so for this I like to have a file called handlers so tasks. handlers. TS and then I can Define my request handlers inside of here so I'll have a request Handler called list and this is essentially going to be a Handler that gets access to the context but we need to make sure we put a type on this thing now there is a built-in type called route Handler and so we can pull that in but this is a

Chapter 35 57:22

tasks list handler

Chapter 36 57:45

RouteHandler type setup

generic type so if you look at it the first argument is a route config type so essentially what we need to do is we need to grab the type of this route and then pass it in to the route Handler here so from this file I'm going to export a type called list route and that's just going to be equal to type of list and so if we look at this this is now a type that defines the specific route and now we want to use it when we're defining our Handler so if I head back over here I then can pass in the list route we'll import it from that file and so now we're getting a type error and it's like hey you're responding with the wrong thing cuz you need to respond with an array of of tasks so let's do that we're going to return just c. Json and here I'll just have some example tasks so like the name will be learn hono and done will be false like that and at this point our type errors should be fixed we just have a linter error that says this variable is unused great so if I just add an export that fixes the linter err uh but check this out if I respond with the wrong type we get a type erir and it's like hey you're missing a property these

are these types are incompatible so property done is missing so now that we've set up the types in this way we are ensured that we are actually responding in the correct way based on our our type definitions and schemas so we'll do that and that looks good now one more thing we need to do is also pass in the app binding so you can see the second generic argument here is EnV and this is actually the app Bindings that we passed into the open API app that we created earlier so for instance if I wanted to access vs. logger I don't have access to that right now you can see that I'm I'm getting a type error so to make sure that I don't get a type error whenever I'm accessing logger or any other variables that I set up I also need to pass in my app bindings here so if I pull in app bindings from my types now we should get type completion so if I do C.V var. logger we get access to it but this is a little bit cumbersome because I don't want to have to Define this type every single time I have a Handler I'm going to have a bunch of handlers inside of my app so we can create a utility type and this is going

Chapter 37 59:48

AppRouteHandler custom type

to require some generics but I'll walk you through it it's going to be just fine I'll Define it in line so you can see what's happening and then we'll pull it out to our our types file but basically I want a type that'll let us do this but not have to pass in the app bindings so if I create a type let's call it the app route Handler we need one thing we need a route config that needs to be passed in so here I can say we'll take in R this is a generic type parameter and we want to say that this must be a route config so by saying extends the type that is passed in must have all the properties of a route config okay so that's our generic argument and then on the right hand side we basically want to do this but we'll use this generic type here and so instead of hardcoding list route we'll just pass in R so now we have this nice reable type where all we have to do is pass in the route config type and it automatically adds those app bindings on so in this case I can do this I don't have to pass in app bindings and now the types flow through so now I can say c.v. logger and I and I still get access

to that so this is really nice because now any route Handler I Define in this file all I have to do is pass in the outout config and then anywhere else in my app as well so let's actually extract this out to our types file so we can reuse it whenever we need it again so I'll head over here to types and then throw it at the bottom add an export on it and then import these things from Zod open API like so sweet and then now over here I can import this in from my types file specifically looking good and at this point I'll just remove all of those unused Imports sweet okay so at this point we have our route Handler we have our route definition now we need to to smack them together right we need to actually add this to our API and so if we look back over here at our route definitions we need to export this specific route definition so that way we can import it into the main router so we've got our route config defined there we've got our Handler Define there now we're going to put them together inside of our router here and so in here I'm going to import all of my handlers in so

Chapter 38 1:01:21

register tasks list route and handler

I'll say import Star as handlers from t. handlers and import Star as routes from pass. routes and now we can use them so we use that buil-in open API method to First specify the route config so here I'm going to say routes. list and then after that I specify the Handler and so I'm going to link that up to handlers.

list and if we did all of our types correctly we should see that there is no type error here because we have our route definition and then this Handler has the correct type to make sure that it matches up with that rout route Handler at this point we should be good to go if we head back over to our API reference and refresh there it is you you can see we have our task inpoint and we can test it out so if I send this we get back an array with an object inside of it sweet now one thing we should do is we should give this group a name right we should call this tasks and we can do that inside of the route definitions so up here I'm just going to create a variable called Tags that has the name of the group like that and then I'll pass this in here so any route that I Define inside of this file I'll always make sure to pass in those same tags and so now when we look at our documentation it's always going to be in that same group called tasks so now instead of instead of just responding with dummy data let's actually get our database up and going and for this we're going to use drizzle o RM and for this we are going to use SQL light so in the docs we'll head to sqlite and I'm actually going to use the docs here under turo so

Chapter 39 1:02:32

tasks route tags

Chapter 40 1:02:55

drizzle setup

the lib SQL client that turo provides can actually just talk to a file on your local machine so when we're running in development we can just talk to a sqlite database living in the same folder and then when we deploy we can create a terso instance and then set our environment variable to be that endpoint uh but for now we'll just set it up and use it local so we going to need all of these dependencies and then we can set up our database instance so I'm going to copy this codes here and then I like to create a folder called DB and then inside of there I create an index.ts and this is going to be our database connection and so we'll import all of this stuff we'll create the client and then export that DV instance as default like so and then from here we'll set these up as environment variables so we're going to specify database URL which is a string we can also verify that it is a valid URL like so and this will be a z. string now I do want database off token to be optional because I don't want to specify it when I'm running locally so I'm going to set

Chapter 41 1:03:50

DATABASE_URL env setup

this to optional but what we can do is we can actually use the refine method which allows us to do further validation and essentially what we can say is we'll we'll call refine here we'll get access to the Pard EnV and we'll say if the node EnV is production then database off token cannot be undefined cannot be empty so we'll say if input. node EnV is equal to production then uh this method returns true or false in terms of is this valid or not and we want to return is uh input. database off token defined so we'll say not not right there uh otherwise we're just going to return true so when we're running locally we don't need to specify database off token but when we're running in production we do need to specify it hello there uh editor CJ here um I actually found that there's a better way to handle this error to make sure we get a good error message if we are missing this environment variable so check out the repo Linked In the description but essentially instead of using refine we

Chapter 42 1:04:52

zod superRefine for better errors

can use super refine add a custom error message here and then if we do come across this error we're going to see a good error message printed out in production now that I have these defined we can head back over and actually use them so right here I can pass in EnV we'll import from there we can say database URL and then this will be env.

off token now if I kill the app and restart it you're going to see that database URL is required and so when we're running locally we can just set that database URL and locally we can set that to a file URL so just say file and then we'll call it dev. DB and then now if I restart the app and the app starts up just fine now let's define our schema and Define that tasks table that's going to hold all of our tasks so I'm going to copy their example table definition here and then we'll modify it so what I'd like to do is in DB I'm going to create another file called schema B this in here and then I'm going to have a table called tasks and then if we head over to the drizzle doc so if we go to column types and then make sure we're under SQL light we can see some examples of like an auto incrementing column so for example we can have an integer ID set the mode to number and then primary key autoincrement true and this will basically make it so that the ID gets automatically created and incremented whenever we insert a new row now another thing we want is a booing because we

Chapter 43 1:05:42

setup drizzle schema

want to know whether or not it's done and in equal light there is no Boolean type but we can create an integer and set the mode to Boolean so with this the property will be either zero or one zero for false one for true and jizel will automatically convert that for us so we're actually working with booleans inside of our codes so right here we'll say that we want done we want this to be called done it's going to be a Boolean it is not null and the default value is false so by default when you insert a task done is going to be set to false and then we also need a task name name so if we check out the docs there is a text type and that's what we'll use so we'll just say the name of this task is text and the column name is name we'll say this cannot be n and then we'll also add created at and updated at columns now sqlite doesn't have a timestamp type but we can use a text type and there's some like built-in helpers so if you head to the drizzle docs go to learn go to tutorials there is one on turo so here you can see that they have this

updated at column which uses an integer mode of timestamp they also have created that which uses text uh but I think I'm going to make Mo both of mine integers and then use this codes here we can get rid of these and we can say that updated at is a timestamp and on update we'll create a brand new date so this is just a built-in hook that'll automatically set that for us and then we'll also have uh created at we'll call it created at timestamp and for this we can use the default method now there's a deprecated function called default now and if you look at it it's actually using this codes here to set the date but they're saying you should do this yourself because there's no direct way to get the current time in milliseconds inside of sqlite they only have time stamp which gives you like a string uh so what we can do is we can say default and then very similar to how they're doing SQL and then passing in some SQL codes here we can say SQL pull that in from drizzle and then pass in a template string and then call the casting code and so essentially this is going to give us

Unix Epoch time anytime a new row is inserted so awesome this looks good to me I'm just going to do a a little bit of formatting here so all of this stuff is easier to read and you can potentially pause the video and make sure that everything looks the same for you like that and you can also check out the the repo that's Linked In the description but this is our database table next up we'll actually push this schema to our local sqlite database and then we can start querying it and also use uh drizzle Studio to look at the database and insert values and different stuff like that and so now to work with Drizzle kit and also create some migrations we need a drizzle config so you can see in their docs here they have an example config we'll go ahead and Define this so in our root we'll create a drizzle. config TTS export that file and now we'll we'll set all this up so the dialect here is going to be sqlite and then for our DB credentials we can pass in the URL and that's just going to come from our EnV so we'll pull that in from our types safe EnV and then pass in database URL and then we can also pass

Chapter 44 1:08:49

drizzle-kit config setup

in the off token which is going to be env. database off token now the other thing is we need to make sure we're pointing at the right schema folder and so my schema is defined inside of source DB and then schema. TS so we want Source DB schema. TS the other thing is I like all my migrations to live in the same folder as the rest of my DB stuff so I'm going to specify that here the migrations should get created in Source DB migrations now this config looks good but I do have one error in my schema so if you head back over to the schema I actually left off some parentheses when we're defining this created at so I do need an opening parentheses there and an open parentheses there so that should be the correct SQL syntax now from here we can generate our migrations so from the command line if I do pnpm drizzle kit generate this should generate a SQL file and it does so if we take a look inside of DB we have a migrations folder and we have that SQL file that's awesome now if

Chapter 45 1:09:59

generate drizzle migrations

we do pnpm drizzle kit push this should push our schema to the database and we should now have a database so because we're working locally and I Define that database URL as dev. DB there it is we have ourselves a little sqlite file that all of our our stuff is going to get written to when we're writing our codes locally uh but right now while I'm thinking about it we should add this to our git ignore because we don't want to push this sqlite file up to GitHub so here inside of my G ignore I'm going to add dev. DB just to make sure that I don't accidentally commit it because every developer that is working on this app would generate and create their own file whenever they're working with it locally uh but now that it exists we can actually start up drizzle kit studio so if I do pnpm drizzle kit Studio this is their built-in webbase tool where we can actually look at our database so if we check it out we have a task table and now we can actually just use the UI here and add some tasks so let's actually just add one and then we'll actually use the database inside of our app whenever we're quering for tasks so let's create

Chapter 46 1:10:51

using drizzle-kit studio

a new task where the name is learn hono enter and then click save we have ourselves a row but now I'm seeing that updated at uh is defaults to null I actually do want it TOA call it to the same created at date so I'm going to update my schema so we have on update but we need to also set the default just going to extract this into a variable we'll just call this uh default Now set it up like that and then I'll also make sure that I pass it in here to say default default now like that sweet hello again editor CJ here uh I ended up just changing how I worked with the dates here to just use JavaScript dates I didn't like how the dates were ending up using that SQL Tim stamp code so here I'm just using the default function and then passing in a new date and I'm doing that for both created at and updated at and another fix is that code that I copied in had the column called update at instead of updated at so I fixed that as well and so I would recommend to keep things simple check out the repo and set up your date columns to look like this

Chapter 47 1:11:27

update schema date logic

uh and now that I've set that up let's go ahead and push the schema so if I do drizzle kit push that'll update the schema and now if I refresh uh whenever we insert a row it should get an updated at column so if we add one here that says uh learn open API and then click save now we get a default updated at field so I'm going to go ahead and delete that other one add another one that just says like learn oh no these are our these are our tasks and then we'll save it sweet so we have two things in the database now let's actually write the code that queries the database whenever we're hitting our API endpoints so if we head back over to routes tasks and then handlers inside of here we can actually query our database so right here I want to grab that DB variable we'll import it in and then I specifically want to query it so built into drizzle you can do db. query and then this is like an Om type of querying where you can do like find mini uh but in order for that to work I do need to let the DB know about my schema so if we

Chapter 48 1:12:44

query db from tasks list handler

head to the DB definition right here we can pass in some options and here I can pass in my schema so what I'll do is I'll import everything from the schema file so I'll say import Star as SCH schema from that specific schema file and so if I were to Define more tables everything that's exported from here we would get inside this variable and then now I'm passing it into the drizzle DB instance and so now that I've done that if I do db. query I get access to tasks and in this case I'm just going to say find Min and so this is going to give me my list of tasks and in this case we are going to respond with that list we need to make sure to await it make this async and we should be good to go so right now our route definition that we defined just said it would respond with an object that has name property and a done property and uh essentially we're doing that because that's what our task schema is now of course we don't want these two things to be out of sync so we'll first

we'll make sure that all of this works but then I'll show you how we can actually get a Zod schema from our database and then use that right here but now let's give it a try so if I head back to my API docs do a refresh and then let's test out the slash tasks point there we go we are reading data from our database which is great so at this point let's get those types hooked up so drizzle has a library called drizzle Zod if we search for it we can see how it's set up once we install it we can pass our table into it and it's going to give us back a Zod validator so if we do this now we can essentially go directly from a table definition to a Zod schema and then use that Zod schema inside of our open API definition so let's install this Library like that but now we'll use the these functions to actually Define our schema so let's head back over to our database schema file and inside of here we want to use these functions and create our schema so first of all we'll do a select schema so I'm going to call this the select tasks

Chapter 49 1:14:28

drizzle-zod setup

schema and this will be create select schema with our specific table tasks cool and then we'll be sure to export that so now we get a Zod schema that exactly describes the type coming from our database and so now if we use this schema inside of our open API definition it will always stay in sync with our table definition here so if we head back over to our route definition now instead of hardcoding this we can actually bring in specifically our select tasks schema so we'll import it from there and just like that our API is up to date and in sync so if we head back over to our API docs so we can see now it has all of those properties defined and those types are flowing through so if we look at show schema it actually generates a Json schema that represents that exact same database table so now it's a beautiful thing our API docs are completely in sync with our database schema so if we ever add new columns or change types or do whatever else our API docs are going to stay up to date and the validation types returned here are going to stay up to date as well now let's create a

Chapter 50 1:16:06

tasks create route

create inpoint so that way we can actually send data to our API to create new tasks so I'm going to copy this route definition and it's going to be called create and the path is still SL tasks but in this case the method is post and now after creating a task we're just going to respond with a single task and so we don't want to use z. array we just want to say the select task schema so after creating you're going to get exactly back the thing that was created in the database uh and the description here is the created task and so now we need to validate the incoming request body so I want to be able to send a post request here with a Json object that has a name in a done property and we should validate that before trying to insert it into the database and so right here I can spef spe ify requests so what's coming in the incoming request and specifically I want to validate the incoming body now the way you specify this is almost exactly the same as the

way you specify responses and I actually have a helper built into my stoker library that creates the same Json content but also adds a required field so for this specific endpoint we want to make sure that the user is always specifying data in the body and if they're not then it should be invalid so this helper here called Json content required will create that with the required property set to true and you can pass in the schema and the description so right here we're going to say Json content required we'll pull that in and then I can specify the schema now for this schema we can actually use the insert schema so if we head back over to our table definition we can create another variable called insert tasks schema we'll say create insert schema which comes from drizzle Zod and then we can pass in our table definition and so now we have a schema which will specifically validate the incoming task now one thing we can do is we can further refine the schema to correspond to the actual data that's

going to be coming into our API so whenever a post request comes in we don't want the user to be able to explicitly set the ID that's automatically generated by the database and we don't even want them to be able to set created at or updated at those should automatically be set as well so what I can do is just using the buil-in omit method from Zod I can specify the properties that I don't want to exist on this schema so I'm specifically going to Omit ID and create at and update at and now I have a Zod validator that does not allow those properties to be passed in but it will still validate name as a string and done as a Boolean so now we can actually use this type so if we head back over to the route definition specifically I want to use insert task schema we'll import that and then we can pass in the description which is the task to create awesome so the route definition is pretty much ready to go let's go ahead and hook it up and see it inside of the API documentation so in my tasks index I'm going to add another

inpoint so we'll say open API we'll say routes. create and right now I'm just going to pass in an empty request Handler now I am getting a type error right because I'm not responding with the correct type but that is just a type error so the app should still be able to spin up and our documentation should still be updated it's just that that inpoint won't actually respond with anything so if I refresh the page you can see that I now have a post in point for SL tasks and then we can see that the expected response looks like this and if we go to test the request we can see an example insert so this example is only including the fields that are required now because the done property has a default value uh it's actually not included here but we can include it so if we head back over to our insert schema we can say do required so this is built into Zod and we'll pass in an object and we'll say that we want that done property to be required like that and so now if I refresh the docs here whenever we look at it we should see that uh a done property is specified for

Chapter 51 1:20:01

tasks create handler

us so now let's actually Implement that request Handler so if we head to our handlers we now want a Handler called create and this is going to be a Handler of type app route Handler create route we'll have to Define that type and then this is going to be a Handler like show but let's define this type here so if we head back over to this file we also want to type which is type of create which is the create route like that and so now if we pull that in we should have a fully typed method here and so the first thing we want to do here is get access to that validated data so if I do c. rec. valid we can then pass in specifically the thing that we're looking for and so we're looking for Json data that got sent to our server so I'll say valid Json we can call this the incoming task we'll just call it task like this and so what's nice about this is the code will never make it here unless the task is actually valid so unless the user actually specified a name and specified

a done column the code will never make it here um but if they do then the code will make it here and we can actually insert it into our database and what's also nice is if for whatever reason extra properties were sent or anything like that those all get stripped away and we only get the data that we specifically care about and that we should be inserting into our database so at this point we can actually insert it let's do db. insert I need to specify the table so I'm going to pull in that tasks table which is defined inside our schema and then here we can specify values and then I can just directly pass in task just like that and so in this case I actually want to return the inserted thing so I will say returning like this and that should give me back the inserted task and now if we look at this this has all of the properties that we expect uh but it is a list right because technically you can insert multiple values so I'm actually just going to wrap this in Brackets to destructure it to just grab that first inserted value and then we can respond with it so I'll just return c. Json like that and our type errors go

away so because we're responding with the thing that we said we would so if we look back over at our route Handler we said that the response will be a task that was selected and here we specifically are selecting a task after inserting it and so we should be good to go now we we still need to hook it up so if you remember we just have that empty request Handler here now we can explicitly specify handlers. create and we can give it a try so if I refresh my docs over here head over test it out let's try inserting a new one we'll say the name is learn drizzle and then click Send and we get back the response and so now if we go back over to our list tasks and run this we should get all of the task including the one that we just created awesome now one other thing we should test is is the validation actually working right and so let's actually test this out here what happens if I send a payload that does not have a done property does does it return an error it does and this is actually

because of our default hook that we set up earlier if you can remember that far back but we get a nice Zod error here that says the done property is required um but one aspect of this is we should actually document this response because if you look at the documented responses right now we're only saying that this thing can respond with a 200 status code but that's not true because if the user or the client sends invalid data it's going to respond with 422 or unprocess entity so we need to handle that inside of our definition um but just to remind you where we actually set this up whenever we create the app so in lib create app right here we're passing in this default hook and this default hook runs if there's ever a validation error from an open API route and it's responding in this way so that default hook comes from my library stoker so if you take a look on mpm there's the method you can Import in and if you look on GitHub you can just look at the source code if you want to see what's happening so if you go into Source open API and then default hook you can see if

the data was not valid we're going to respond with success as false and then that actual Zod error and then we're using the unprocessable entity error code so this is a 422 error code so as long as you have that set up you should be getting this validation response if you send invalid data to the API but we need to document that invalid response so if we head back over to our route definitions right here we are saying that yes this API can respond with a 200 status code but we can also respond with a 422 so let's document it we can say HTTP status codes. unprocessable entity which is 422 uh and if you're if you're unfamiliar with these status codes you can hover over and uh the docs include what it is and what it's used for um so there's that and in this case we want to describe the potential error that we might get back uh so it is going to be Json so we can say Json content and then you provide a schema right now I'm just going to give a blank one so we can get this just working for now and then a description and so here we'll say uh the

validation errors like so but to document this in the right way I essentially need a schema that describes all of the possible issues that could go wrong when validating this specific type and I built a helper for it so if you look at the stoker Library there is a schema called create error schema and the idea is you can pass any Zod schema into it and it's going to create examples that correspond to that specific type and essentially all I've done under the hood I'll show you tell you that code in a second is I've literally described a Zod object that has a success property an error property which has an issues property which is an array etc etc uh but I don't want to have to Define that manually so if you look in my repo open API and then schemas and then create error schema there's a bit of typescript Foo and generics going on here but essentially there's that type but the cool thing is I explicitly create an error type by

Chapter 52 1:25:06

stoker createErrorSchema helper

attempting to parse an empty object so basically I run parse first to give us back an example error and then I pass that in right here and so that way whenever we're looking in our API docs I'll be able to see a 422 Tab and see an example of that error so if anybody is ever reading the docs they can see oh I potentially could get a name is required error or a done is required error so we're just going to pull in this type for my library but again if you don't want to use my library you can copy paste it create your own uh but right here all we have to do is say create error schema and then pass in the schema which is the insert task schema like that and so now if we head back to our documentation we should see that the 422 status code is specified and we see an example error that it's possible that name might be missing and so it sends back uh required or that done might be missing and so like I said basically all I do is run the Zod validator on an empty object or an empty array and just get back the response and then use that

as the example so essentially whatever your validations might be it's it's just going to be those top level validations but this is nice and documented now so when someone comes along and tries to create something uh without a done property they get back this response but they could already see in the documentation what happens now one thing is once you start to describing multiple response types now you explicitly need to set your status codes inside of your request handlers so if we take a look back at our handlers we're actually getting a type error now because uh it's hard to read but here we're saying the status code can be 200 or 422 and we didn't pass in a status code so in order for all the types to work in the right way we need to explicitly say what this status code is so right here I'll just pull in HTTP status codes and then when I respond I'll explicitly say this is an okay response or a 200 status code and now typescript is happy because I've explicitly set the response code now one other thing I'd like to do is actually update this validator because what I

Chapter 53 1:27:46

customize drizzle-zod schema

realized is we have no validation on like empty strings or the length of strings and so if I were to send this with the done property then we would have like empty empty tasks in our database so what we can do is just update our validator so if we head back to our schema right now on our insert schema we can actually modify the existing validators and so this create insert schema method actually accepts a second argument which can be an object so here I can specify any column and then modify the existing validator that exists for these so for instance if I want to add some validation to name I can do this pass in a call back this gets access to the Zod schema and then here I can say schema. name dot Min for instance so I can set the minimum length to one and now this validator will not accept empty values but you can do this for any field and you can modify it in any way so for instance let's say this was like an email field there's a built-in email validator inside of Zod

so you actually could chain it and you can say email boom you now have instant email validation for any incoming data um but in this case I'll set Min to one we could even set a Max right if we if we want to make sure that our database doesn't get overloaded so maybe I set the max to like 500 and now the the maximum task size you could send uh is of length 500 uh and so with that our documentation should be updated as well right and so if I head back to the docs and refresh we can see now that those validations are listed in the docs so it says name has a minimum length of one and a maximum length of 500 and so if I try sending an empty name boom will not happen string must contain at least one characters and so now I actually have to pass in a name like learn Zod and we'll set that to false because we still got some learning to do and now that should insert it into the DB now let's create an inpoint where we can get a single task by ID so right now if we get all the tasks you can see they each have a unique ID but we want to be able to get an individual one by ID at like task

Chapter 54 1:29:37

tasks getOne route

slid so let's set that up here inside of my routes I'll Define a new one called get one and so I'm just going to copy the one from list we're going to rename it to get one and then now I need to specify the ID in the path so if a request comes into task SL2 that should return the task with id2 so here I can do slash and then specify that we have an ID in the URL there and if you take a look at the docs for hono Zod open API you can see an example of this here so they have a route user slid then they have an actual validator for that ID because we should validate is this a number or if like you had a uh like a uyu ID in the path you could add a validator for uu IDs explicitly uh or or whatever else you need to validate uh but in this case we can prevent the Handler from even running if there is an invalid ID that was sent in so you can see they specify a validator and then there's the open API method where they chain it and they can say that this is a

Pam whose name is ID and it's in the path so as long as you set up your schema like this it should work now this is something we do very often so I added it to my stoker Library so if you look at stoker we have under schemas the ID pams schema if you for instance are needing to validate that an ID is an integer you can pass that in and if you take a look in the codes it's going to be in open API schemas and then ID prams and it's super straightforward right it's literally just ID in path but one thing I am doing here is I'm using the built-in coer so that way I can actually use it as a number inside of the request Handler so Zod do coers can take in a string and then coers it to a number if it is a number uh so we can use this pram schema and I don't have to Define it manually every time I I need it so let's do that right here so here we can say request and then we can say pams and I'll bring in the ID pams schema which

is defined there inside of stoker and in this case our valid response is just a single task so it's not a z array it is just a task TK that got selected from the DB and here the description is the requested task so let's hook this up so we can see it in our documentation and then after that we will implement it so over here I need a new inpoint we'll say open API we'll say routes. git one and then again we're just going to pass in an empty Handler for now but we'll Implement that soon so if I go back to my docs refresh we now have an inpoint which is tasks slid uh we can see that ID has to be a number and let's actually try it out first of all just make sure that the validation of the ID prams works so if I pass in a string here that's obviously not a number so if we try to hit this endpoint we get that validation error that says expected number received Nan and again this is responding with that 422 status code so it's using the same default hook and responding accordingly and so with

that in mind we should add a response that says hey you could potentially get a validation error so it's going to be very similar to our create route so if we head back over to our route definitions we're going to want an unprocess entity documentation that creates an error schema for the ID prams right so this is the validation that we're doing in this case if the Pam ID is not a valid number then we're going to get an error and in this case I'll actually describe it as invalid ID error and so now that we have that when we look at the API docs we can see that it might possibly respond with the 422 where the ID is not a number so now third verse same as the first let's implement it we'll head back over to our handlers and we explicitly need a Handler called git one and I'm just going to copy list and we'll update it accordingly but we're going to rename this to git one and then we're going to need a type called the get one route and so back over in my route definitions I will

Chapter 55 1:33:17

tasks getOne handler

create a type the get one route and it's the type of get one like so now we will pull that type in and in this case we can actually use the find first method of drizzle and we'll pass in awar Clause uh but we need to get the D so we can do that using c. rec. valid just like we did for the body so this is going to give us back the params if I say c. rec.

valid and then pass in Ram you'll see this is an object which has an ID property which is a number and just like before the code will never make it here unless that ID is actually a number and so in this case I'm just going to destructure it so now I have the ID and then I can query accordingly so with Drizzle we can pass in aware Clause here and I'm just going to return uh operate ators do equal so I want to check to see that the ID field is equal to the ID that got passed in there and so this is going to get turned into a select from task where ID equals ID limit one because it's the first one and then we can respond with it and in this case it's either going to be that task that was in the database or it could be undefined right because this potentially could not be in the database so uh first of all I'll just call it task and then I'll respond with it here but just like before I'm going to specify the status code so this is a valid response let's make sure that this works let's actually

hook it up and then we'll make sure that we handle not found but right here we'll say handlers. get one and then now if we head here and test it out if we request with id2 that gives us back the task with id2 or id5 there we go but if we pass in something that doesn't exist we should just get back like undefined yeah it it can't even parse because we're responding with nothing uh so we need to handle that and first of all we should document it right so if we head over to our route documentations the possible responses for this endpoint are yes it's okay you got back the thing from the database or no it's not okay you passed in an invalid ID or the thing was not found so we're going to make sure we document that as well and here we'll say it's the HTTP status code not found and in this case we can just do uh Json content and in this case we'll just respond with an object and a message property so the schema here will be a z.

object and the message will be a string like that and the description here will just be task not found and we can also document this so if we do open API here and we pass in uh example we can say the message is not found like that so now we're documenting a 404 and if we head back to our docs and we look at this we can see that there's a possible 404 here where you get a not found message uh but we need to handle that right so inside of our Handler after requesting from the DB if the task is not defined then we need to respond with a not found message so if task is not defined then we're actually just going to return c. Json pass in the object uh but if I want to get type completion I should pass in the status code first because then it knows how to validate that type so if I passed in the status code as not found and now inside of here I can specify the message as not found and our type completion is good to go so now we're actually handling all cases right we're handling is there an invalid ID in the pams was

the task not found and actually responding with the task itself so now if we try it out and I send a request for something that doesn't exist in the database it responds with not found awesome now this is something that we do fairly often in our apis is responding with like a a not found message and so I actually have a helper built in to stoker that includes a Zod validator for a message property so what I'll do is instead of defining it in line here I'm actually going to Define some constants so that way any other API endpoints that need to respond with a not found message they don't have to redefine it every time so here inside of lib I'm going to create a file called constants and inside of here I'll create the not found schema and that's just going to be uh create message object so I'll pull that in from stoker like that and then I need to pull in the HTTP status phrases like this and now I have a schema specifically that validates a message and has an example for not found so I'll make sure that I export this and then

now any inpoint that needs to respond with not found can reuse this validator so I'm not redefining it in multiple places so right here I'll just include the not found schema and then pull that in from constants the other thing is inside of my request Handler I should use those status phrases as well right so right now I'm just hardcoding not found but if I include phrases. not found that's like the canonical uh phrase associated with that status code and then I don't have any hardcoded strings so right here I can HTTP status phrases. notfound and so if we look back at the docs it should be exactly the same but now any other routes that Define a not found Handler can just reuse that schema so we we're reducing a lot of duplication here um and I have a typo ask not found all right and the last endpoint that we need to implement is patch so I want to be able to update an existing task by ID so let's set it up now this one is going to be a combination of like the get one route

Chapter 56 1:38:37

tasks patch route

and the create route because we're validating the incoming body but we're also validating the incoming paths so we're actually going to copy the create and then paste it and call it patch and the method will be patch but the path will be for a specific ID so patch task sl5 is going to allow you to partially update the task with id5 so we can actually copy this other stuff from the git one route so for patch the path is going to be tasks slid uh the method is patch not get and then we want to validate the pams as well as the incoming request body so you can see that this is a combination of all of these so when the request comes in first of all is it a valid ID we're going to validate that first if it is awesome after that we'll validate the body and so this these are the properties that are being updated like name or done uh and in this case we'll give it a better name so this is not the task to create

this is the updates we'll say the task updates and then for responses so this will still be the select task schema because we are going to be retrieving it from the database but the description is different this is the updated task and then now we have two possible validation errors right it's possible that the ID is invalid but it's also possible that the data they sent us in the body is invalid so for this we actually need to specify that the response for unprocessable entity can be one of either of those two you could potentially do this schema or and then pass in create error schema for the ID prams schema now we are getting a type error because right now my Json content helper function doesn't accept Zod unions I'll probably update it by the time you see this video so you can can pass in Union but if we specify it like this let's check it out so if I refresh my reference and then head over to patch we can see that here are the possible issues and if we click on show schema

you can see that it uses any of and so it does pass in those two schemas so we have the one schema for validating the body with name and done and then we have the other schema which is for validating that invalid Pam in the URL but any of isn't what we actually want to use uh there's a good article here that talks about using one of or any of or all of inside of your open API schemas and specifically they talk about any of and mention that for a lot of code generators this creates potential issues so what ultimately what we really want is one of it can be either one of these two things not like a combination of them and so to get this working I wrote a helper method inside of stoker and it's called Json content one of and so basically you can use this helper method and then just pass in an array of schemas and then the generated docs will include all of the possibilities using one of instead of any of now the code for this is a little bit tricky because you actually do have to use methods from the underlying libraries like Zod to

open API and types from open API 3 uh but you can see how I implemented it so if you check out the stoker Library go to open API and then take a look at helpers and then specifically look at the one of helper so essentially what I had to do is pull in the open API generator and actually generate the specs for each of these schemas and then I return that and then the wrapper of one of is Json content one of and it essentially uses that helper there to get an array of schemas so in order to use these functions we actually do need to install separate dependencies because behind the scenes it's going to have to run that generator you can see in the docs it mentions that we have this as a dependency so I'm going to install this like that and now we can try to use it so instead of calling Json content we're going to call Json content one of and then we can pass in an array so instead of using a union with or we can just pass in an array that uses both of these

schemas so we'll do something like this and so now the generated docs will use that one of key with these two schemas instead of the any of now for most purposes you might not need this but if you are using any sort of code generation tool with the output of your spec here this is definitely something you would potentially want to use so now that I have that set up if we head back to our API and refresh we can take a look and when we look at the schema for 422 we can see that it's using one of now the one major difference of a patch request over a create request is that all of our properties are optional and right now if we look at the insert task schema both the done and name properties are actually required so in order to make this patchable we need a schema where name and done are optional and for that there's a built-in method in Zod so what we can do is create a schema so we're going to call this the patch tasks schema and we're going to use the insert task so we'll say insert task schema but then we can use the partial method so

this is just built into Zod and now if we look at our schema it accepts both name and done but both of those are optional so now let's actually use this schema in in our patch method so over here whenever we are receiving the body it is a patch schema we'll import that and then our validation errors should use the patch schema as well and now with this we're ready to actually Implement that patch route so we'll head over to our handlers we're going to copy over the git one and we're going to rename this to patch and we need the type so this is going to be the type of patch route so let's go Define this type like so so it's a typ of patch and then we'll import that type here and now we can attempt to update it so we can grab the incoming body with c. rec. valid Json and if we look at it this is going to be an object with a name or a done property both of them can be undefined because this is just a patch so you can send just the name or send just done

Chapter 57 1:44:08

tasks patch handler

then we can run the update query so for this we'll say db. update we'll pass in the table which we already have a reference to in this file there and then we will set and we can pass in those values and in this case I can just directly pass in updates but we need a wear Clause so we only want to set these updates where the ID is equal to the ID that was in the URL so I'll add a wear Clause here and then we'll need to bring in EQ so EQ is a helper function here from drizzle omm we can pass in the column that we're comparing in this case it's tasks. ID and the value that we're comparing it to which is the ID we got from the URL uh last ly we will do returning and so this will return a list of all of the updates and in this case because it's returning a list we just want to grab the first one like that and essentially this will handle our not found scenario for us so if we try to update something in the database and it can't find it by ID we're not going to get anything back from the updates so

essentially if we didn't get anything back we know that this wasn't even found in the database and we can respond with a not found but if it was updated we should get back the actual values and then we can return it um but I'm remembering so we're getting a type error here we actually didn't set up the response where if the status code is not found so we need to make sure that we set that up in our route definition to get rid of that type error so if we head back to our routes we also need the not found response and I'm just going to copy this over from our get one and so now this inpoint will either respond with the task that was updated respond with a four4 not found or respond with validation errors either validation errors in the URL or validation errors in the body so with that our type errors look good let's actually hook it up so if we head back over to task. index now we can actually pass in that Handler so here if we say handlers. patch we should be able to update things so we'll refresh the docs now if we look at it we can see all of the documented potential

responses so not found or the potential validation messages but now let's test it out so first of all let's just list the uh tasks in our API again and we'll figure out which one we're going to update and so let's update task id5 and so right now done is set to false we want to set that to true so if we test our patch method and we pass in id5 and then in the body we set done to true it should work and it does so it responds and it tells us that yes it was updated and we can see the updated at column was actually updated there uh so if we make a request for all tasks we should see yes now that is set done to True awesome I we can even check our individual route here so if we do a get request here for task with id5 and then send it over done is set to True awesome but let's actually test the potential not found situation right so let's try to run a patch for a task with an ID

that is not found it responds with not found great now the last endpoint we need is for deleting tasks so let's get that going if we head over to the route definitions we need one more definition for delete and for this I'm just going to copy the patch route because it's going to be fairly similar I'm going to call this one remove mainly because delete is a was a reserved word so we'll call this remove um but the HTTP method will be delete it will be for a specific ID so if we receive a delete request at some ID will then attempt to delete it now in this case we don't accept anything in the body we're just going to be looking at the ID pram and whatever that ID is we'll attempt to delete it and for delete we are actually going to change the success status code to be no content so if you delete something we won't respond with the thing from the database we'll just say yes we deleted that and the body will be completely empty so the status code here is going to be no content which is uh 204 and

Chapter 58 1:47:41

tasks remove route

then in this case we're just going to pass in the description so we can pass an object here and then the description will just be task deleted uh we will have a not found response right if someone sends a delete request for an ID that's not in our database we are going to send not found and then we potentially will also have a validation error uh if the ID prams are wrong so in this case we can just go back to Json content pass in the ID pams schema like this and then we'll update the description to say uh invalid ID error okay so now while I'm thinking about it let's go Ahad and create the type you got the type of the remove route and now we'll head over to our handlers and we'll Implement remove I'm just going to copy over our patch rename it to remove and then we'll bring in the remove route type and in this case we just need to pull in the ID of the thing that we're deleting and here instead of update we can say delete like that and then we can

Chapter 59 1:49:17

tasks remove handler

remove the set and then in order to know if something is deleted or not we can actually just look at the result so if we don't return anything result is a result set and we should be able to see the number of rows modified and if that is zero then the task was not found so here we'll say result. rows affected and this is a number and we'll say if that is zero then that means nothing was deleted so in a sense the task was not found uh if we did delete it we just want to respond with nothing so we can actually do c. body and then pass in null and then here we can pass in the specific status code so if we do HTTP status codes. no content like that that should be what we need so if it's deleted just respond with nothing just uh a 204 status code now let's hook it up so if we head over here we can add one more route we'll do routes. remove

and then handlers. remove okay so we'll refresh our docs now we have our our delete task here and we will give it a try so the examples are 204 no content so it's if it's a successful deletion then it responds with nothing it's possible that it's not found then it's also possible that you gave us a bad ID in the URL so first of all let's just test a bad ID like that we get an error awesome Let's test deleting something that doesn't exist we get it not found and then let's test deleting a task with id5 it gets deleted we get 204 no content and so now if we list the task out again we can see that task with id5 is removed so we've done it we have create read update delete for our list of tasks it's fully documented we've got lots of type safety it's pretty great so before I go do want to show you how we can potentially test these routes now I'm not going to write all of the tests here in this video we've been basically doing developer testing by using the docks here but a good production ready

Chapter 60 1:51:15

test setup / helpers with vitest

API also has tests within the code so I want to show you how we'd set that up so if you look in the hono Dos under guides there is a testing section and what is really nice is any of the routers that we have created already has a request method built into it so if we want to write tests we don't even need a separate Library like typically when you're testing Express you need something like super test but this is just built into hono so you can literally do router. request pass in the URL the options and then write some tests against that response the other thing is they actually have a fully typed test helper built in so you can actually pass your app into this test client and then you get the fully typed RPC very similar to the client RPC so this is something that I actually haven't shown yet we'll do this after we look into tests but hono supports RPC and that if you've defined your endpoints with validators you can actually just export the type of your app directly and then use that on the

client side so we'll show that next but this test helper here is basically the same thing but now inside of your tests you get a fully typed client where you can just get access to all of the methods that you've Define so to show this working I'm going to write a super basic test for the list route so what I like to do is I put my tests directly next to the files that they're testing I actually don't like to have a separate test directory because it makes it a lot easier to navigate back and forth between the code and the test itself so here I'm going to create a file called tasks.

test.ts now in order to test we need a testing library for that I'm just going to use vest it's super simple to set up I can just do mpmi DD vest and then I'll add a test script so here in my scripts we'll say test and in order to test we just run vest it's literally that simple vest we'll search our whole directory for any file that has the word test inside of it um but actually I'm not sure does it find plural tests we we will see but let's write a test but we can bring in uh describe and so here we can Define our test Suite so I'm going to describe T list so this is going to specifically test our our list Handler and then in here we can define a unit test so I'll bring in it from v test and we'll say it responds with an array so super basic test like I said we're not going to write a full test Suite just want to show you how this works so what we'll do is we're just going to import the router so the router is defined in here we'll just import import it in and then directly call request on it so here I'll say router we'll import it in from

tasks /index and then I can just say router. request so this is buil in and I can just pass in anything so if I make a request for slash list let's actually see what happens we'll grab the response we'll need to make this an async method and then let's actually try looking at the result here so I'm going to await response dot I'm just going to use text cuz we could run into an issue where we don't get back Json let's see and for now I'm just going to log out that result and we're going to write a failing test so I'm going to expect false to be true so we should get a failing test but we should also see what the result is of calling get against slash list so you can think of request just like fetch you essentially pass in a URL but then you can also pass in options where it specifies the method and everything else so by default it's going to do a get request so let's see what happens in my terminal if I just do mpm run test vest should find my test

file and then run them but like I was suspicious of earlier it has to be called test not tests so I'm going to remove the plural there and now it should detect it and we'll run test H toad URL does this file exist I have a feeling this has to do with our typescript aliases let me let me do some searching of the web so I found this stack Overflow issue where they do specify that you have to also specify the Alias inside of your v test config so it's not exactly as instant as I thought it would be so let me go ahead and Define this so just at the root we're going to create a vest I'm just going to push it I'm going to try to create a typescript file and then uh we'll run all of this uh we don't want any plugins um I don't want test globals literally all I want is I want the at to resolve to the source directory so let's see if setting up that config does it for us yes okay so the tests are

actually running we have a failing test cuz we expected false to be true but I'm curious what did we see this is it and this is what I was worried about you can see that when we're logging out the response here it's literally just the text 404 not found and if you remember we actually set up our app so that even a 404 would respond with a Json object but that's not the case right now and the reason is we are actually accessing that router directly and this router that we defined right here doesn't have any of the middle Wares that we Define for our overall application so in order to make sure that everything is behaving in the way that we would expect we basically need to wrap this in an app that also has all of the middle Wares and everything else and so if you remember back to the beginning of this video when we created this function that's why I I extracted this function here because I want to do this same thing and then mount my router and then create that like as a test client so from here I'm just going to export a function called uh create test app and

so this is going to accept a router and that router is just of type open API hono app bindings uh but if you remember we actually did Define a reusable type yeah this app open API type so we can actually use this type here and say that our router is of that type because when we create a router it's open API hono with those app bindings um but essentially what we want to do is we want to create a test app just by calling create app function that we created earlier and then we want to mount this router at the root just like we did on our our main app so if I say test app. route we're going to put it on slash and we're going to pass in that router there and so now I have my router but it has all the same middle Wares and error handlers and everything else that it has when it's running in the context of the full application and so this is what we can run our tests against uh now I do need to import this type so yeah we'll import that from types and then from here I'll return the test app and so now I can use this function inside of my tests and run the request against it

instead so here I can say the test router is create test app with my router we'll import that function from there and now instead of using the router we'll use the test router and now I would expect that when we log the result here it should actually be a Json object because it has all of the not found middle Wares and everything else and so if we take a look there it is it is the not found object great now I didn't even do this on purpose slash list is like the wrong URL so if we really want to test this thing uh the actual endpoint we look at our routes is slash tasks so right here if I request slash tasks that's going to give us back a response I then know that we're going to get back Json data so I can then do this and then this should be an array I'm just going to log it so we can actually see the data and so now I'm just going to expect that the result is an array so we have the expect type of from vest we'll expect the type of result to be array

now we get a type error because right now the thing that we get back is the any type so I'm actually just going to add a TS expect error and then I'm going to allow this for the entire file so typically when you are writing tests um you kind of have to ignore typescript errors for certain scenarios when you're doing your testing but now I'm going to ignore the type error expect it to be an array and all the tests are passing Sweet so this is how you would test essentially each one of your folders that has routes inside of it you can create a test file create that test app and then start poking and prodding at it and so now we'll test it again but let's use the built-in test client so I'll add another unit test it responds with an array again I said these are not in-depth tests um but one thing we want to do is now pass this router into the test client so we can pull in the test client we'll say uh test client and then pass in that test router like so now if typescript is working and I've done

Chapter 61 1:59:23

typed test client helper

everything right this will have the right type it doesn't so I've played around with this a lot we might actually just need to Define this in line so that all of our types kind of flow through so here's what I'm going to do and you can refactor like the create test app functions depending on on how this works so first of all I'm just going to create an app so I'll call this the test app without passing in the router and we'll just say create uh app right and so that's that's the function that we defined like at the beginning of the video that just gives us a basic hono app with all of our middlewares but now if I say the test router is test app.

rout slash and then pass in our router there what I want to see is so here we can see the actual type right we see the paths the methods Etc but on this I want to see that same type and I do and so now this is what we can pass in there um ultimately we could try here returning directly test app. route that wasn't working for me so you might actually just do this in line and you could even write a helper function in this file that does something like this um and then we can inline this whole thing so create app and then route at that router and now we have a fully typed client so check this out instead of just passing in manual requests we actually get a typed client that's similar to the RPC client so if we do client dot we can see all the stuff that's available so we can say tasks and then we can see all of the possible things and so in this case we want to run the git request which is going to list all of our tasks and I'll call this response so we'll await that and then the Json is going to be

awaiting response. Json and the way this typed client works is if you check the status code then your Json data will be of a specific type and so right now yeah I guess for our get all tasks inpoint it only has one response type but for the other types where it might have like 404 not found or unprocessable entity Json can be several different things right depending on the response um but in this case we should be able to inspect it directly I should just be able to expect the type of Json to be and array like that and we don't have to do TS expect error because uh it explicitly knows that this is an array of items here and so if we look at our tests we can see that it has passed now one thing that's happening as well is you're actually seeing all of the request logs like the debug logs and stuff like that happening if you don't want to see those when you're running tests you can actually just update log level so inside of the package.json here we can set a log level

to silent and then if we kill the this and rerun it everything breaks so it looks like whenever I set this up I didn't include silent in the enum I'm all over the place but let's actually fix that so if we go back to our EnV it is possible for the log level to be silent so let's save that kill this restart it okay it's happy and now it runs my tests without all of the the logs happening uh in in clouding up the console so that's one way to do it I will say if you're running this on Windows you might need to pull in the package called cross EnV uh before being able to just pass environment variables so let me just show you that really quick if you check out cross-v on npm you'd want to install this package and then inside of your scripts use cross CMV so that's especially if you have multiple people on your team that are like using different operating systems but for mine this this works perfectly fine now one more test I'll show you is uh the possibility of having different types of responses based on the Response Code so let's actually say um so let's create a

test we'll say it validates the ID par and so we'll create that same test client and then now we'll attempt to do tasks at a specific ID and then we'll call get on that and you can see here we get a type error because it actually wants us to pass that param in so here I need to pass in an object then I pass in a Pam and then I can specify the ID and so if I pass in W then this should respond with that 422 status code unprocessable entity um and so first of all let's write a failing test so I could expect response. status to be and let's just expect it to be 200 um I need to make sure that I pull expect in from v test and now we should have a failing test we run the tests yes so uh that inpoint responds with 422 because the ID is not a number and so to get a passing test we can expect this to be 422 like that cool all right like I said I'm not going to

write all of these tests cuz we've basically been testing manually but this is how you can get tests going and get really nice type completion um I would especially combine this with TS expect error because I'm going to write another test just to demonstrate this but let's say we're sending data to the API right so let's say it validates the body when creating um if we attempt to make a request to tasks. poost so we're going to try to create a new task we'll get a type error because we need to pass in the Json body and so in this case the way you pass it in is with the Json prop and then we can specify the properties here but you'll see we're getting type completion so when I'm creating a new task I need to pass in the name and done so here I'll set name to learn vest um but let's say I want to get a 422 status code um then I'm not going to pass in the done property and so I should expect this to be 422 but let's expect it to be

200 just so we get a failing test but yeah it's 422 because it's actually validating that then we get a passing test but this is a scenario where if you're using this typed test client you would just throw this TS expect error right here cuz you're explicitly testing to make sure that it's validating missing properties so this is a scenario where you can ignore the typescript errors okay so this video is taking longer to make than I thought anyways so I might as well show you how to get your tests up and going um so if you take a look at the starter repo that's Linked In the description you can see all of the code for how this is going I'm just going to point at some of the more relevant parts now essentially what I did is I pulled out this test client that's fully typed and I put it at the top of my test file here so so now in any one of my tests I can use that fully typed test client and then from there I want my tests to be able to use their own isolated test database so I also set up a test EnV file and this essentially just points to a test DB file but whenever we run our tests we explicitly loading in that EnV so if you look at our typ safe EnV we are checking to see if we're in the test environment and if

Chapter 62 2:05:33

full test setup walkthrough

we are in the test environment we'll load in that test environment variable file otherwise we'll load in the normal one and so essentially whenever these tests are running they create their own isolated test database they do all of their testing against that database and then when the tests are done the database gets completely removed and so if we take a look at that test file essentially before the tests start running we just run drizzle kit to push the schema to that database and then after the tests are done running we just delete that database now the other thing to look at is for all of these tests we're specifically using the status code to get really good type safety and so the way that the hono client works is if you have an if statement that checks the status code then the type of the return of response. Json will specifically correspond to the type that you specified in your schema for that status code so for most of these tests you can see that I'm actually checking the status code and then poking in proding at the responses to make sure they are what I expect uh and so here I have a full test Suite that tests all of the endpoints and so if you run mpm test that's going to create that test database run all the tests against it and then delete that test database and

so this is a really good starting point if you want to make sure that you have really good tested endpoints you can basically look at this file as a reference for all of the other route groups that you create now one last thing I'll show you is how we can actually get a typed client for our entire application and so up until this point we've just been testing in the browser but what's nice about hono is we can actually infer the types of all of these defined routes and get a fully typed client that we can use like inside of our client side code like in react and it works exactly the same as I was showing you here inside of this test client where basically it has all of the endpoints documented and type errors for all of the stuff that you pass in essentially there's way to export the type and then use this on the client side and the way that we can get this going is if we head over to app essentially what we want is a type that represents every single router that's inside of this array and so that's why I've defined it in this array as our application grows we're going to create more and more routers and if we put them

Chapter 63 2:07:20

hono RPC client type

in this array we can actually infer the type of everything that's inside of that array and so the first thing I'll do is I'll set this as const and so this just lets typescripts know that this array is not going to change at runtime and it's going to allow us to actually get the type out of it and then to get that type we can set type as app type and essentially what we want is a union type of everything that's inside of this Ray so what I'm going to do is I'm going to say type of routes at number and so this will give me the type of everything at a number so 0 one and so if we look at app type now this is a type that represents all of the possible routes within my application and if I export this all I'll need to do is import this type into my client side code and then I can pass this into the hono client so just like they're passing in the app type here this is the type that I would pass in there now this is one way that I found to do it I I like doing this another way you can do it is instead of defining these in an array is you can actually chain the route method and so right here

we can say app. route and then we can pass in the index route and then we can chain it we'll say app. route and then we'll pass in tasks Etc so any other routes you have to find and then store the return value of this so here I can just call this like underscore app and then get the type of this so if I say export app type we'll set this equal to type of app just like that and this should work in exactly the same way because by chaining these methods all of the types of each of those individual routes get inferred and then we can use the type here but I prefer the array method because the more routes that you get the longer and longer this chain is going to get so it's pretty nice that if you have everything defined in a single array like this you can just iterate over it mount it all and then use the types like this now to just show an example of this here in lib let me create a client file and we'll actually import that type and attempt to create a hono client so we can import hon client

Chapter 64 2:09:57

hono client example

we can then try to create a client in this case we're at Port 9999 and then we'll import that app type from app and so when you're running this inside of client side code you absolutely want to make sure that that you import the type and not the the full thing because if you're running client code then all of that's going to error out and a lot of times you would potentially be doing this inside of a mono repo so you would basically have like one folder that has your API and then another folder that has your client and then you're able to share the types between them in this case I'm just writing some quick client code to show you how it works so now that we've passed that type in there I can do client Dot and you can see all the things we have available so the index route is just that that homepage that returns a Json object so we can do that we can also access tasks and then get access to all of those endpoints just like we were doing inside of the tests uh but this is great because you can actually do this like I said inside of client side code okay but I'm going to delete that file because one of the aspects of using open API is there are actually generators for like every type

Chapter 65 2:11:03

open api client generators

of language so you can literally take this specification here pass it into those client generators and they'll actually generate like a client SDK so you could literally generate an SDK called my tasks AP and it will be fully typed have all the methods and and validators and everything else um and like I said they have support for tons of different languages so if you're building your backend with typescript but your client isn't typescript like maybe it's a swift app or an Android app then you could use one of those generators to generate an SDK and then be able to call your API in a fully typed way as well now like I mentioned at the beginning of the video our hono app is defined inside of its own file and this is completely agnostic of anything specific to any of these run times and so if you want to deploy to anyone one of these run times essentially what you need to do is take a look at index.ts and then adapt this to deploy to the specific runtime that you'd like to deploy to now I was running into some issues when I attempted to deploy this to versell and it mainly comes down to the fact that I am using path aliases and they don't have support for that unless you're

Chapter 66 2:11:40

runtime and deployment considerations

actually like building and bundling your code so I'm going to save that for a future video let me know down in the comments if that's something that you want to see uh but yeah we're going to reserve deployment for a future video so that's all the time I have for in this video thank you so much for watching hopefully you learn something new even if you're an existing hono developer but if you're brand new to hono hopefully I gave you a good introduction and you're going to go build some awesome apis uh definitely check out the link in the description it has a link to the starter repo everything's documented you can kind of like look through all of this codes and also give it a star if you like it and check out the package I wrote called stoker which basically removes a lot of the boilerplate whenever you're building out these apis with hono and hono zad open API that's it for this one there's a ton more I could cover about hono and open API I want to cover things like Authentication and tokens and token expiry and all of that other stuff that we didn't get to talk about here and so if there's anything specific you'd like to know about building apis with hono or open API let me know down in the comments and I'll be sure to work on that in a future video all right that's it for this one I'll see you in the next one

Chapter 67 2:12:17

Thanks!

[Music] a [Music]

Quote it with credit and a link. Quoting Syntax