├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── client ├── index.d.ts └── index.js ├── images ├── Screen Recording 2021-11-04 at 2.00.46 PM.gif ├── Screen Recording 2021-11-04 at 2.08.22 PM.gif └── Screen Recording 2021-11-04 at 2.13.55 PM.gif ├── index.d.ts ├── index.js ├── package-lock.json ├── package.json ├── server ├── index.d.ts └── index.js └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [0.6.4] 10 | 11 | ### Changed 12 | 13 | - Fixed MIME parsing bug 14 | 15 | ## [0.6.3] 16 | 17 | ### Changed 18 | 19 | - More generous MIME type parsing 20 | 21 | ## [0.6.2] 22 | 23 | ### Changed 24 | 25 | - Accept both `200 OK` and `304 Not Modified` as successful status codes 26 | 27 | ## [0.6.1] 28 | 29 | ### Changed 30 | 31 | - add type: module 32 | 33 | ## [0.6.0] 34 | 35 | ### Changed 36 | 37 | - Make the route the first argument to `makeHandler` 38 | 39 | ## [0.5.0] 40 | 41 | ### Changed 42 | 43 | - Remove all .ts files and commit hand-written .js and .d.ts directly to repo 44 | 45 | ## [0.4.4] 46 | 47 | ### Changed 48 | 49 | - Rename `next-rest/api` to `next-rest` 50 | 51 | ## [0.4.3] 52 | 53 | ### Changed 54 | 55 | - Maintenance release 56 | 57 | ## [0.4.2] 58 | 59 | ### Changed 60 | 61 | - Maintenance release 62 | 63 | ## [0.4.1] 64 | 65 | ### Changed 66 | 67 | - Refactor away from compsite TypeScript build mode 68 | 69 | ## [0.4.0] 70 | 71 | ### Changed 72 | 73 | - Restructure exports to support TypeScript 4.4 74 | 75 | ## [0.3.1] 76 | 77 | ### Changed 78 | 79 | - Require TypeScript 4.5+ 80 | 81 | ## [0.3.0] 82 | 83 | ### Added 84 | 85 | - This changelog! 86 | - Add a nice Standard Readme 87 | 88 | ### Changed 89 | 90 | - Refactored to use subpath exports and TypeScript build mode 91 | 92 | [unreleased]: https://github.com/joeltg/next-rest/compare/v0.6.4...HEAD 93 | [0.6.4]: https://github.com/joeltg/next-rest/compare/v0.6.4 94 | [0.6.3]: https://github.com/joeltg/next-rest/compare/v0.6.3 95 | [0.6.2]: https://github.com/joeltg/next-rest/compare/v0.6.2 96 | [0.6.1]: https://github.com/joeltg/next-rest/compare/v0.6.1 97 | [0.6.0]: https://github.com/joeltg/next-rest/compare/v0.6.0 98 | [0.5.0]: https://github.com/joeltg/next-rest/compare/v0.5.0 99 | [0.4.4]: https://github.com/joeltg/next-rest/compare/v0.4.4 100 | [0.4.3]: https://github.com/joeltg/next-rest/compare/v0.4.3 101 | [0.4.2]: https://github.com/joeltg/next-rest/compare/v0.4.2 102 | [0.4.1]: https://github.com/joeltg/next-rest/compare/v0.4.1 103 | [0.4.0]: https://github.com/joeltg/next-rest/compare/v0.4.0 104 | [0.3.1]: https://github.com/joeltg/next-rest/compare/v0.3.1 105 | [0.3.0]: https://github.com/joeltg/next-rest/compare/v0.3.0 106 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Joel Gustafson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # next-rest 2 | 3 | [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg)](https://github.com/RichardLitt/standard-readme) [![license](https://img.shields.io/github/license/joeltg/next-rest)](https://opensource.org/licenses/MIT) [![NPM version](https://img.shields.io/npm/v/next-rest)](https://www.npmjs.com/package/next-rest) ![TypeScript types](https://img.shields.io/npm/types/next-rest) 4 | 5 | Typesafe REST APIs for Next.js. 6 | 7 | ## Table of Contents 8 | 9 | - [Background](#background) 10 | - [Install](#install) 11 | - [Usage](#usage) 12 | - [Defining runtime types](#defining-runtime-types) 13 | - [Augmenting the API module](#augmenting-the-api-module) 14 | - [Exporting the route handler](#exporting-the-route-handler) 15 | - [Using the API client](#using-the-api-client) 16 | - [Error handling](#error-handling) 17 | - [Contributing](#contributing) 18 | - [License](#license) 19 | 20 | ## Background 21 | 22 | This library is a framework for writing **end-to-end** typesafe JSON REST APIs for Next.js in TypeScript. 23 | 24 | Features: 25 | 26 | - **Modularity**. Instead of making you define all of your route types in one place, next-rest uses module augmentation so that you can declare each route's type in their own respective file. All of the logic for an API route `/api/foo/bar` is contained in the `/pages/api/foo/bar.ts` page. 27 | - **Minimalism**. The client API is 100 lines and just calls `fetch` like you'd expect. next-rest has one non-dev dependency on [http-status-codes](https://www.npmjs.com/package/http-status-codes). All validation happens on the server; using next-rest won't cause your validation library to get bundled into the client. 28 | - **Safety**: next-rest lets you write APIs where the URL parameters, request headers, request body, response headers, and response body are all (!!) strongly typed for each combination of route and method. All of your API calls get typechecked at compile-time by TypeScript _and_ validated at runtime on the server. 29 | 30 | Limitations: 31 | 32 | - **JSON-only**. next-rest is JSON-only. 33 | - **Internal use only**. next-rest is designed for implementing and calling REST APIs **within** a single Next.js application. You can't export your API types, or import a different project's API types. If _that's_ what you're after, you probably want something like [restyped](https://github.com/rawrmaan/restyped/). 34 | - Requires TypeScript 4.4+, Next.js 12+, and React 17+ 35 | 36 | ## Install 37 | 38 | ``` 39 | npm i next-rest 40 | ``` 41 | 42 | ## Usage 43 | 44 | There are four basic steps. Most of the work happens inside the API route pages - once you've set those up right, you can just `import api from "next-rest/client"` from any client page or component and things will work like magic. 45 | 46 | ### Defining runtime types 47 | 48 | next-rest is designed to be used in conjunction with a validation library like [io-ts](https://github.com/gcanti/io-ts), [runtypes](https://github.com/pelotom/runtypes), or [zod](https://github.com/vriad/zod). Anything that supports a) static type inference and b) gives you [type predicates](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) for your types will work. The code samples here use io-ts. 49 | 50 | Let's write a route `/api/widgets/[id]` that supports `GET` and `DELETE` methods. The first thing we have to do is make io-ts codecs for our request headers and response bodies. For methods that don't accept content in the request body, we'll use `t.void`. 51 | 52 | ```ts 53 | // pages/api/widget/[id].ts 54 | 55 | import * as t from "io-ts" 56 | 57 | const getRequestHeaders = t.type({ accept: t.literal("application/json") }) 58 | const getRequestBody = t.void 59 | 60 | const deleteRequestHeaders = t.type({ "if-unmodified-since": t.string }) 61 | const deleteRequestBody = t.void 62 | ``` 63 | 64 | These serve as "runtime representations" of types. We also need type-level versions of those types, which we can get with the `t.TypeOf` utility type. 65 | 66 | ```ts 67 | // pages/api/widget/[id].ts 68 | 69 | type GetRequestHeaders = t.TypeOf 70 | type GetRequestBody = t.TypeOf 71 | type DeleteRequestHeaders = t.TypeOf 72 | type DeleteRequestBody = t.TypeOf 73 | ``` 74 | 75 | Lastly, we need types for our response headers and response bodies. These don't need to be validated at runtime (since it's the server that sends them), so we can just write them as normal TypeScript types. 76 | 77 | ```ts 78 | // pages/api/widget/[id].ts 79 | 80 | type GetResponseHeaders = { 81 | "content-type": "application/json" 82 | "last-modified": string 83 | } 84 | 85 | type GetResponseBody = { 86 | id: string 87 | isGizmo: boolean 88 | } 89 | 90 | type DeleteResponseHeaders = {} 91 | 92 | type DeleteResponseBody = void 93 | ``` 94 | 95 | ### Augmenting the API module 96 | 97 | The central problem in designing a end-to-end typesafe API is finding a way to share types between server and client code without sharing anything else (ie without accidentally bundling actual server code into the client). We do this with next-rest by augmenting the `API` type in the `next-rest` module inside every API route page. These augmentations get merged and the client code in `next-rest/client` is able to access the merged API type by also importing `next-rest`. 98 | 99 | ```ts 100 | // pages/api/widget/[id].ts 101 | 102 | declare module "next-rest" { 103 | interface API { 104 | "/api/widgets/[id]": Route<{ 105 | GET: { 106 | request: { 107 | headers: GetRequestHeaders 108 | body: GetRequestBody 109 | } 110 | response: { 111 | headers: GetResponseHeaders 112 | body: GetResponseBody 113 | } 114 | } 115 | DELETE: { 116 | request: { 117 | headers: DeleteRequestHeaders 118 | body: DeleteRequestBody 119 | } 120 | response: { 121 | headers: DeleteResponseHeaders 122 | body: DeleteResponseBody 123 | } 124 | } 125 | }> 126 | } 127 | } 128 | ``` 129 | 130 | Notice that the each entry is wrapped in a `Route<...>`. The `Route` type is just defined as `Route = T` and is just used to typecheck the method implementation. You don't have to `import` or `export` the `API` or `Route` types inside the `declare module "next-rest" { ... }` block; they're already in the module scope. 131 | 132 | ### Exporting the route handler 133 | 134 | The last thing to do in each server-side API route page is export the actual API handler. Next.js expects the default export to be a function `(req: NextApiRequest, res: NextApiResponse) => void` which we create by calling the `makeHandler` method exported frun `next-rest/server`. 135 | 136 | `makeHandler` takes a string API route as its first argument. The second argument is a configuration object that contains - for each method supported by the route - [custom type predicates](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) for the request headers and bodies, and an `exec` method implementing the actual handler for that method at that route. 137 | 138 | You should be able to get custom type predicates from your runtime validation library. For io-ts, they're the `.is` property of the codec, like `getRequestHeaders.is: (value: unknown) => value is { accept: "application/json" })`. 139 | 140 | Implementing the exec method is where the magic starts kicking in: it takes a single `{ params, headers, body }` argument, but you don't have to declare any types. TypeScript knows to infer `params` from the route path parametrizing `makeHandler` (!!) and to infer `headers` and `body` from the augmented API module. 141 | 142 | The exec method must return a Promise resolving to an object `{ headers, body }`. TypeScript will already know to expect the correct response headers and response body types and will complain if you don't provide them. 143 | 144 | ```ts 145 | // pages/api/widget/[id].ts 146 | 147 | import { makeHandler } from "next-rest/server" 148 | 149 | export default makeHandler("/api/widgets/[id]", { 150 | GET: { 151 | headers: getRequestHeaders.is, 152 | body: getRequestBody.is, 153 | exec: async ({ params, headers, body }) => { 154 | // TypeScript knows the types for all of these! 155 | // - var params: { id: string } 156 | // - var headers: { accept: "application/json" } 157 | // - var body: void 158 | 159 | // ... do implementation stuff 160 | const { isGizmo, updatedAt } = await prisma.widgets.findUnique({ 161 | where: { id: params.id }, 162 | select: { isGizmo: true, updatedAt }, 163 | }) 164 | 165 | return { 166 | headers: { 167 | "content-type": "application/json", 168 | "last-modified": new Date(updatedAt).toUTCString(), 169 | }, 170 | body: { id: params.id, isGizmo }, 171 | } 172 | }, 173 | }, 174 | DELETE: { 175 | headers: deleteRequestHeaders.is, 176 | body: deleteRequestBody.is, 177 | exec: async ({ params, headers, body }) => { 178 | // TypeScript knows the types for all of these too! 179 | // - var params: { id: string } 180 | // - var headers: { "if-unmodified-since": string } 181 | // - var body: void 182 | 183 | // ... do implementation stuff 184 | const updatedAt = new Date(headers["if-unmodified-since"]).toISOString() 185 | const { count } = await prisma.widgets.deleteMany({ 186 | where: { id: params.id, updatedAt: { lte: updatedAt } }, 187 | }) 188 | return { headers: {}, body: undefined } 189 | }, 190 | }, 191 | }) 192 | ``` 193 | 194 | Putting it all together, our complete sample API route page `pages/api/widget/[id].ts` looks like this: 195 | 196 | ```ts 197 | import * as t from "io-ts" 198 | 199 | import { makeHandler } from "next-rest/server" 200 | 201 | const getRequestHeaders = t.type({ accept: t.literal("application/json") }) 202 | const getRequestBody = t.void 203 | 204 | const deleteRequestHeaders = t.type({ "if-unmodified-since": t.string }) 205 | const deleteRequestBody = t.void 206 | 207 | type GetRequestHeaders = t.TypeOf 208 | type GetRequestBody = t.TypeOf 209 | type GetResponseHeaders = { 210 | "content-type": "application/json" 211 | "last-modified": string 212 | } 213 | type GetResponseBody = { id: string; isGizmo: boolean } 214 | 215 | type DeleteRequestHeaders = t.TypeOf 216 | type DeleteRequestBody = t.TypeOf 217 | type DeleteResponseHeaders = {} 218 | type DeleteResponseBody = void 219 | 220 | declare module "next-rest" { 221 | interface API { 222 | "/api/widgets/[id]": Route<{ 223 | GET: { 224 | request: { 225 | headers: GetRequestHeaders 226 | body: GetRequestBody 227 | } 228 | response: { 229 | headers: GetResponseHeaders 230 | body: GetResponseBody 231 | } 232 | } 233 | DELETE: { 234 | request: { 235 | headers: DeleteRequestHeaders 236 | body: DeleteRequestBody 237 | } 238 | response: { 239 | headers: DeleteResponseHeaders 240 | body: DeleteResponseBody 241 | } 242 | } 243 | }> 244 | } 245 | } 246 | 247 | export default makeHandler("/api/widgets/[id]", { 248 | GET: { 249 | headers: getRequestHeaders.is, 250 | body: getRequestBody.is, 251 | exec: async ({ params, headers, body }) => { 252 | // ... method implementation 253 | return { 254 | headers: { "content-type": "application/json" }, 255 | body: { id: params.id, isGizmo: false }, 256 | } 257 | }, 258 | }, 259 | DELETE: { 260 | headers: deleteRequestHeaders.is, 261 | body: deleteRequestBody.is, 262 | exec: async ({ params, headers, body }) => { 263 | // ... method implementation 264 | return { headers: {}, body: undefined } 265 | }, 266 | }, 267 | }) 268 | ``` 269 | 270 | ### Using the API client 271 | 272 | Now that we've implemented our route on the server and augmented the `next-rest` module, we can start using the client API! 273 | 274 | The client api is the default export of `next-rest/client`, and it's an object of functions for every HTTP method. This means you invoke the api like this: 275 | 276 | ```ts 277 | import api from "next-rest/client" 278 | 279 | api.get("/api/widgets/[id]", { params: { id }, headers, body }) 280 | api.delete("/api/widgets/[id]", { params: { id }, headers, body }) 281 | ``` 282 | 283 | The first argument to the method function is the API route **without** any dynamic route parameters - e.g. `/api/widgets/[id]`, not `/api/widgets/81903281`. The second argument is an object with `params`, `headers`, and `body` properties. The `params` object is where you provide values for the dynamic route (`{ id: "81903281" }`). 284 | 285 | Here's an example component page at `components/widget.ts` that renders a widget and has a button that lets the user refresh the widget's `.isGizmo` property. 286 | 287 | ```tsx 288 | // components/widget.ts 289 | 290 | import React, { useCallback } from "react" 291 | 292 | import api from "next-rest/client" 293 | 294 | interface WidgetProps { 295 | id: string 296 | isGizmo: boolean 297 | } 298 | 299 | export function Widget(props: WidgetProps) { 300 | const [isGizmo, setIsGizmo] = useState(props.isGizmo) 301 | const [isChecking, setIsChecking] = useState(false) 302 | 303 | const checkGizmoStatus = useCallback(() => { 304 | setIsChecking(true) 305 | api 306 | .get("/api/widgets/[id]", { 307 | params: { id: params.id }, 308 | headers: { accept: "application/json" }, 309 | body: undefined, 310 | }) 311 | .then(({ headers, body }) => { 312 | // TypeScript knows these types! 313 | // - var headers: { "content-type": "application/json" } 314 | // - var body: { id: string; isGizmo: boolean } 315 | setIsGizmo(body.isGizmo) 316 | }) 317 | .catch(() => alert("could not check gizmo status")) 318 | .finally(() => setIsChecking(false)) 319 | }, []) 320 | 321 | return ( 322 |
323 |

i'm a widget!

324 |

and i {isGizmo ? "am" : "am NOT"} a gizmo

325 | 331 |
332 | ) 333 | } 334 | ``` 335 | 336 | Notice the total lack of type annotation around the API call! In fact, as soon as you start typing `api.get`, you'll see something like this: 337 | 338 | ![VSCode autocompleting the API routes that support GET requests](./images/Screen%20Recording%202021-11-04%20at%202.00.46%20PM.gif) 339 | 340 | TypeScript knows which API routes support GET requests - in this case there's just one - so it'll offer to autocomplete them for you. And once you select one, TypeScript will parametrize the rest of the API call with the types for that specific method: 341 | 342 | ![VSCode autocompleting the route params, request headers, and request body](./images/Screen%20Recording%202021-11-04%20at%202.08.22%20PM.gif) 343 | 344 | ... and when we get our result, TypeScript knows what's inside our response headers and body as well: 345 | 346 | ![VSCode autocompleting the types of the response headers and response body](./images/Screen%20Recording%202021-11-04%20at%202.13.55%20PM.gif) 347 | 348 | ### Error handling 349 | 350 | If you throw an error from inside a method implementation on the server (ie inside one of your `exec` functions), next-rest will by default respond to the request with status code 500. If you want to control this, you can import `ServerError` from `next-rest/server` and throw one of those instead: 351 | 352 | ```ts 353 | declare class ServerError extends Error { 354 | readonly status: number 355 | constructor(status: number, message: string) 356 | } 357 | ``` 358 | 359 | For example, we could modify our DELETE implementation to return a more informative status code in cases where the `if-unmodified-since` condition fails: 360 | 361 | ```ts 362 | // pages/api/widget/[id].ts 363 | 364 | import { StatusCodes } from "http-status-codes" 365 | import { makeHandler, ServerError } from "next-rest/server" 366 | 367 | export default makeHandler("/api/widgets/[id]", { 368 | // ... 369 | DELETE: { 370 | headers: deleteRequestHeaders.is, 371 | body: deleteRequestBody.is, 372 | exec: async ({ params, headers, body }) => { 373 | const updatedAt = new Date(headers["if-unmodified-since"]).toISOString() 374 | const { count } = await prisma.widgets.deleteMany({ 375 | where: { id: params.id, updatedAt: { lte: updatedAt } }, 376 | }) 377 | 378 | if (count === 0) { 379 | // This will cause next-rest to set the response status code to 412 380 | throw new ServerError( 381 | StatusCodes.PRECONDITION_FAILED, 382 | "you've got stale data, man!!" 383 | ) 384 | } 385 | 386 | return { headers: {}, body: undefined } 387 | }, 388 | }, 389 | }) 390 | ``` 391 | 392 | There is a symmetric class `ClientError` exported from `next-rest/client` that we can use to handle this on the client as well. 393 | 394 | ```ts 395 | class ClientError extends Error { 396 | readonly status: number 397 | constructor(status: number, message: string) 398 | } 399 | ``` 400 | 401 | If the client receives any response other than 200, it will throw an instance of `ClientError` containing the status code and the response body as text. 402 | 403 | ```ts 404 | import { StatusCodes } from "http-status-codes" 405 | import api, { ClientError } from "next-rest/client" 406 | 407 | function deleteWidget(id: string, updatedAt: string) { 408 | api 409 | .delete("/api/widgets/[id]", { 410 | params: { id }, 411 | headers: { "if-unmodified-since": new Date(updatedAt).toUTCString() }, 412 | body: undefined, 413 | }) 414 | .then(({ headers, body }) => alert("widget deleted successfully")) 415 | .catch((err) => { 416 | if ( 417 | err instanceof ClientError && 418 | err.status === StatusCodes.PRECONDITION_FAILED 419 | ) { 420 | console.error(err.message) // "you've got stale data, man!!" 421 | alert( 422 | "could not delete widget because the request was made with stale data" 423 | ) 424 | } else { 425 | alert("unknown error while deleting widget") 426 | } 427 | }) 428 | } 429 | ``` 430 | 431 | ## Contributing 432 | 433 | If you find a bug or have a suggestion, feel free to open an issue to discuss it! 434 | 435 | ## License 436 | 437 | MIT © 2020 Joel Gustafson 438 | -------------------------------------------------------------------------------- /client/index.d.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | API, 3 | RequestBody, 4 | ResponseBody, 5 | RequestHeaders, 6 | ResponseHeaders, 7 | Params, 8 | } from "../index.js" 9 | 10 | export declare class ClientError extends Error { 11 | readonly status: number 12 | constructor(status: number, message: string) 13 | } 14 | 15 | declare const methods: { 16 | get: ( 17 | route: R, 18 | request: { 19 | params: Params 20 | headers: RequestHeaders<"GET", R> 21 | body: RequestBody<"GET", R> 22 | } 23 | ) => Promise<{ 24 | headers: ResponseHeaders<"GET", R> 25 | body: ResponseBody<"GET", R> 26 | }> 27 | put: ( 28 | route: R, 29 | request: { 30 | params: Params 31 | headers: RequestHeaders<"PUT", R> 32 | body: RequestBody<"PUT", R> 33 | } 34 | ) => Promise<{ 35 | headers: ResponseHeaders<"PUT", R> 36 | body: ResponseBody<"PUT", R> 37 | }> 38 | post: ( 39 | route: R, 40 | request: { 41 | params: Params 42 | headers: RequestHeaders<"POST", R> 43 | body: RequestBody<"POST", R> 44 | } 45 | ) => Promise<{ 46 | headers: ResponseHeaders<"POST", R> 47 | body: ResponseBody<"POST", R> 48 | }> 49 | head: ( 50 | route: R, 51 | request: { 52 | params: Params 53 | headers: RequestHeaders<"HEAD", R> 54 | body: RequestBody<"HEAD", R> 55 | } 56 | ) => Promise<{ 57 | headers: ResponseHeaders<"HEAD", R> 58 | body: ResponseBody<"HEAD", R> 59 | }> 60 | patch: ( 61 | route: R, 62 | request: { 63 | params: Params 64 | headers: RequestHeaders<"PATCH", R> 65 | body: RequestBody<"PATCH", R> 66 | } 67 | ) => Promise<{ 68 | headers: ResponseHeaders<"PATCH", R> 69 | body: ResponseBody<"PATCH", R> 70 | }> 71 | delete: ( 72 | route: R, 73 | request: { 74 | params: Params 75 | headers: RequestHeaders<"DELETE", R> 76 | body: RequestBody<"DELETE", R> 77 | } 78 | ) => Promise<{ 79 | headers: ResponseHeaders<"DELETE", R> 80 | body: ResponseBody<"DELETE", R> 81 | }> 82 | } 83 | 84 | export default methods 85 | -------------------------------------------------------------------------------- /client/index.js: -------------------------------------------------------------------------------- 1 | import StatusCodes from "http-status-codes" 2 | 3 | export class ClientError extends Error { 4 | constructor(status, message) { 5 | super(message) 6 | this.status = status 7 | } 8 | } 9 | 10 | const optionalRestComponentPattern = /\[\[\.\.\.(.+)\]\]^$/ 11 | const restComponentPattern = /\[\.\.\.(.+)\]^$/ 12 | const componentPattern = /^\[(.+)\]$/ 13 | 14 | function makeURL(route, params) { 15 | const path = [] 16 | for (const component of route.split("/")) { 17 | if (optionalRestComponentPattern.test(component)) { 18 | const [{}, param] = restComponentPattern.exec(component) 19 | if (param in params) { 20 | const values = params[param] 21 | if (Array.isArray(values)) { 22 | for (const value of values) { 23 | path.push(encodeURIComponent(value)) 24 | } 25 | } else { 26 | throw new Error(`Invalid URL rest parameter: ${param}`) 27 | } 28 | } 29 | } else if (restComponentPattern.test(component)) { 30 | const [{}, param] = restComponentPattern.exec(component) 31 | const values = params[param] 32 | if (Array.isArray(values)) { 33 | for (const value of values) { 34 | path.push(encodeURIComponent(value)) 35 | } 36 | } else { 37 | throw new Error(`Invalid URL rest parameter: ${param}`) 38 | } 39 | } else if (componentPattern.test(component)) { 40 | const [{}, param] = componentPattern.exec(component) 41 | const value = params[param] 42 | if (typeof value === "string") { 43 | path.push(encodeURIComponent(value)) 44 | } else { 45 | throw new Error(`Invalid URL parameter: ${param}`) 46 | } 47 | } else { 48 | path.push(encodeURIComponent(component)) 49 | } 50 | } 51 | return path.join("/") 52 | } 53 | 54 | function parseHeaders(headers) { 55 | const result = {} 56 | for (const [key, value] of headers) { 57 | result[key] = value 58 | } 59 | return result 60 | } 61 | 62 | async function clientFetch(method, route, params, headers, body) { 63 | const mode = "same-origin" 64 | const init = { method, mode, headers } 65 | if (body !== undefined) { 66 | init.body = JSON.stringify(body) 67 | } 68 | 69 | const url = makeURL(route, params) 70 | const res = await fetch(url, init) 71 | if ( 72 | res.status !== StatusCodes.OK && 73 | res.status !== StatusCodes.NOT_MODIFIED 74 | ) { 75 | throw new ClientError(res.status, await res.text()) 76 | } 77 | 78 | const responseHeaders = parseHeaders(res.headers) 79 | const contentType = res.headers.get("content-type") 80 | const mimeType = parseMimeType(contentType) 81 | if (mimeType === "application/json") { 82 | const responseBody = await res.json() 83 | return { headers: responseHeaders, body: responseBody } 84 | } else { 85 | return { headers: responseHeaders, body: undefined } 86 | } 87 | } 88 | 89 | function parseMimeType(contentType) { 90 | if (typeof contentType === "string") { 91 | const index = contentType.indexOf(";") 92 | if (index === -1) { 93 | return contentType 94 | } else { 95 | return contentType.slice(0, index) 96 | } 97 | } else { 98 | return null 99 | } 100 | } 101 | 102 | const makeMethod = 103 | (method) => 104 | (route, { params, headers, body }) => 105 | clientFetch(method, route, params, headers, body) 106 | 107 | export default { 108 | get: makeMethod("GET"), 109 | put: makeMethod("PUT"), 110 | post: makeMethod("POST"), 111 | head: makeMethod("HEAD"), 112 | patch: makeMethod("PATCH"), 113 | delete: makeMethod("DELETE"), 114 | } 115 | -------------------------------------------------------------------------------- /images/Screen Recording 2021-11-04 at 2.00.46 PM.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joeltg/next-rest/e1b36f939cc3a65210f734a83adb4c0ea4881bc5/images/Screen Recording 2021-11-04 at 2.00.46 PM.gif -------------------------------------------------------------------------------- /images/Screen Recording 2021-11-04 at 2.08.22 PM.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joeltg/next-rest/e1b36f939cc3a65210f734a83adb4c0ea4881bc5/images/Screen Recording 2021-11-04 at 2.08.22 PM.gif -------------------------------------------------------------------------------- /images/Screen Recording 2021-11-04 at 2.13.55 PM.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joeltg/next-rest/e1b36f939cc3a65210f734a83adb4c0ea4881bc5/images/Screen Recording 2021-11-04 at 2.13.55 PM.gif -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import type { IncomingHttpHeaders, OutgoingHttpHeaders } from "http" 4 | 5 | export interface API {} 6 | 7 | export type Route = T 8 | 9 | type RouteSignature = Partial> 10 | 11 | export interface MethodSignature { 12 | request: { 13 | headers: IncomingHttpHeaders 14 | body?: any 15 | } 16 | response: { 17 | headers: OutgoingHttpHeaders 18 | body?: any 19 | } 20 | } 21 | 22 | export type Methods = "GET" | "PUT" | "POST" | "HEAD" | "PATCH" | "DELETE" 23 | 24 | type GetMethodSignature = R extends keyof API 25 | ? API[R] extends RouteSignature 26 | ? M extends keyof API[R] 27 | ? API[R][M] 28 | : never 29 | : never 30 | : never 31 | 32 | export type RequestBody< 33 | M extends Methods, 34 | R extends keyof API 35 | > = GetMethodSignature extends MethodSignature 36 | ? GetMethodSignature["request"]["body"] 37 | : void 38 | 39 | export type ResponseBody< 40 | M extends Methods, 41 | R extends keyof API 42 | > = GetMethodSignature extends MethodSignature 43 | ? GetMethodSignature["response"]["body"] 44 | : void 45 | 46 | export type RequestHeaders< 47 | M extends Methods, 48 | R extends keyof API 49 | > = GetMethodSignature extends MethodSignature 50 | ? GetMethodSignature["request"]["headers"] extends IncomingHttpHeaders 51 | ? GetMethodSignature["request"]["headers"] 52 | : never 53 | : never 54 | 55 | export type ResponseHeaders< 56 | M extends Methods, 57 | R extends keyof API 58 | > = GetMethodSignature extends MethodSignature 59 | ? GetMethodSignature["response"]["headers"] extends IncomingHttpHeaders 60 | ? GetMethodSignature["response"]["headers"] 61 | : never 62 | : never 63 | 64 | export type RoutesByMethod = { 65 | [R in keyof API]: M extends keyof API[R] ? R : never 66 | }[keyof API] 67 | 68 | export type MethodsByRoute = { 69 | [M in keyof API[R]]: M extends Methods ? M : never 70 | }[keyof API[R]] 71 | 72 | export type Params = 73 | R extends `/[[...${infer OptionalCatchAllParam}]]${infer OptionalCatchAllRest}` 74 | ? { [P in OptionalCatchAllParam]?: string[] } & Params 75 | : R extends `/[...${infer CatchAllParam}]${infer CatchAllRest}` 76 | ? { [P in CatchAllParam]: string[] } & Params 77 | : R extends `/[${infer Param}]${infer Rest}` 78 | ? { [P in Param]: string } & Params 79 | : R extends `/${string}/${infer Rest}` 80 | ? Params<`/${Rest}`> 81 | : {} 82 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "next-rest", 3 | "version": "0.6.4", 4 | "type": "module", 5 | "description": "Typesafe REST APIs for Next.js", 6 | "files": [ 7 | "index.js", 8 | "index.d.ts", 9 | "server", 10 | "client" 11 | ], 12 | "main": "index.js", 13 | "types": "index.d.ts", 14 | "exports": { 15 | "./": { 16 | "types": "./index.d.ts", 17 | "default": "./index.js" 18 | }, 19 | "./client": { 20 | "types": "./client/index.d.ts", 21 | "default": "./client/index.js" 22 | }, 23 | "./server": { 24 | "types": "./server/index.d.ts", 25 | "default": "./server/index.js" 26 | } 27 | }, 28 | "scripts": { 29 | "test": "echo \"Error: no test specified\" && exit 1" 30 | }, 31 | "repository": { 32 | "type": "git", 33 | "url": "git+https://github.com/joeltg/next-rest.git" 34 | }, 35 | "author": "Joel Gustafson", 36 | "license": "MIT", 37 | "bugs": { 38 | "url": "https://github.com/joeltg/next-rest/issues" 39 | }, 40 | "homepage": "https://github.com/joeltg/next-rest#readme", 41 | "devDependencies": { 42 | "react": "^17.0.2", 43 | "react-dom": "^17.0.2", 44 | "typescript": "^4.4.4" 45 | }, 46 | "peerDependencies": { 47 | "next": "^12.0.2", 48 | "react": "^17.0.2 || ^18.0.0", 49 | "react-dom": "^17.0.2 || ^18.0.0" 50 | }, 51 | "dependencies": { 52 | "@types/node": "^16.11.6", 53 | "@types/react": "^17.0.34", 54 | "@types/react-dom": "^17.0.11", 55 | "http-status-codes": "^2.1.4" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /server/index.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import type { IncomingHttpHeaders } from "http" 4 | import type { NextApiRequest, NextApiResponse } from "next" 5 | 6 | import type { 7 | API, 8 | Params, 9 | MethodsByRoute, 10 | RequestBody, 11 | ResponseBody, 12 | RequestHeaders, 13 | ResponseHeaders, 14 | } from "../index.js" 15 | 16 | export declare class ServerError extends Error { 17 | readonly status: number 18 | readonly message: string 19 | constructor(status?: number, message?: string) 20 | } 21 | 22 | type Handler = ( 23 | req: NextApiRequest, 24 | res: NextApiResponse, R>> 25 | ) => void 26 | 27 | type Input> = { 28 | params: Params 29 | headers: RequestHeaders 30 | body: RequestBody 31 | } 32 | 33 | type Output> = { 34 | headers: ResponseHeaders 35 | body: ResponseBody 36 | } 37 | 38 | type MethodImplementation> = { 39 | headers: (headers: IncomingHttpHeaders) => headers is RequestHeaders 40 | body: (body: unknown) => body is RequestBody 41 | exec: (request: Input) => Promise> 42 | } 43 | 44 | type Methods = { 45 | [M in MethodsByRoute]: MethodImplementation 46 | } 47 | 48 | export declare const makeHandler: ( 49 | route: R, 50 | methods: Methods 51 | ) => Handler 52 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | import { StatusCodes, getReasonPhrase } from "http-status-codes" 2 | 3 | export class ServerError extends Error { 4 | constructor( 5 | status = StatusCodes.INTERNAL_SERVER_ERROR, 6 | message = getReasonPhrase(status) 7 | ) { 8 | super(message) 9 | this.status = status 10 | this.message = message 11 | } 12 | } 13 | 14 | const hasMethod = (method, methods) => method in methods 15 | 16 | const error = (res, code) => res.status(code).end(getReasonPhrase(code)) 17 | 18 | export const makeHandler = (route, methods) => async (req, res) => { 19 | if (req.method === undefined || !hasMethod(req.method, methods)) { 20 | return error(res, StatusCodes.METHOD_NOT_ALLOWED) 21 | } 22 | 23 | const implementation = methods[req.method] 24 | if (!implementation.headers(req.headers)) { 25 | return error(res, StatusCodes.BAD_REQUEST) 26 | } 27 | 28 | const body = req.body || undefined 29 | if (!implementation.body(body)) { 30 | return error(res, StatusCodes.BAD_REQUEST) 31 | } 32 | 33 | const result = await implementation 34 | .exec({ params: req.query, headers: req.headers, body }) 35 | .then((right) => ({ _tag: "Right", right })) 36 | .catch((left) => ({ _tag: "Left", left })) 37 | 38 | if (result._tag === "Right") { 39 | const { headers, body } = result.right 40 | for (const key of Object.keys(headers)) { 41 | res.setHeader(key, headers[key]) 42 | } 43 | 44 | res.status(StatusCodes.OK) 45 | if (body === undefined) { 46 | res.end() 47 | } else { 48 | res.json(body) 49 | } 50 | } else if (result.left instanceof ServerError) { 51 | const message = result.left.message 52 | res.status(result.left.status).end(message) 53 | } else { 54 | return error(res, StatusCodes.INTERNAL_SERVER_ERROR) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "module": "ES6", 5 | "target": "ES2020", 6 | "moduleResolution": "node", 7 | "allowSyntheticDefaultImports": true, 8 | "declaration": true 9 | } 10 | } 11 | --------------------------------------------------------------------------------