As far as TypeScript type checking goes, the methods are known because at typing time, we import this type from the server. And this is a type only import, so it doesn't create a dependency between the client and server code. But it imports this type, and then we pass that into Cat and Web here. And Cat and Web will actually cause this thing to have a type that makes it look like it has all the right methods on it. Of course, if you prefer not to import directly from your server code, you could factor out a separate TypeScript interface file and have them both import that, too. It all works.
So before I go further on the interesting features of Cat and Web, I want to set up an example case. So let's say we are building a chat API or a chat service like a Slack or a Discord. And this is a basic REST API for that, for a simplified version of that. Now, I'm expressing this informally because, as you'll see in a bit, if I tried to express it formally, it gets too complicated. But this is very simple, straightforward. We have an endpoint to get a list of all room names. We have an endpoint to get messages, the chat history from a particular room, take some query parameters, return some messages. We have an endpoint to post a new message to a particular room. And all of these require authorization, so that might come in the form of an authorization header or maybe a cookie.
Now, let's say we want to convert this API to Cat and Web, and we're just going to do it in the sort of naive, straightforward way. We're going to convert each of these endpoints to a method on our chat API. So list rooms, get history, send. And with HTTP, we have a lot of different places in the request where you can put the inputs, but in Cat and Web, you only have one. It's just the method parameters. So we have to take all the things that were in an HTTP request and make them parameters here. The token ends up being a parameter to every single one of these methods. There's no URL. We put the room name as a parameter, etc. And then we can reuse these TypeScript types that we defined before. So what does the code end up looking like? So on the left, we have a code to call our REST API. And since it's an HTTP API, you have to call fetch, and you have to do sort of a lot of this boilerplate stuff around setting up HTTP requests. It gets a little ugly. And in practice, no one actually writes this raw code.
Comments