0.1.0 • Published 3 years ago

@kienleholdings/nextjs-api-utils v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

NextJS API Utilities

Tooling to build better, more secure APIs with Next.js

Installation

yarn add @kienleholdings/nextjs-api-utils

Usage

This package exposes several modules and scripts, the following documentation should cover most use cases

Building API Handlers

import { createHandler } from '@kienleholdings/nextjs-api-utils';

// Available methods include get, post, patch, put, and delete
const handler = createHandler({
  get: (req, res) => {
    // TODO: Write handler
  },
});

export default handler;

Using Standardized Responses

import { apiResponse } from '@kienleholdings/nextjs-api-utils';

...

const get = (req, res) => {
  // Sends a 200 response with a JSON body { "data": "foo" }
  apiResponse.ok(res, { data: 'foo' });
};

...

Using Standardized Middleware Stack

This includes a body parser, body validator, and CORS middleware (unconfigured by default)

import { withMiddleware } from '@kienleholdings/nextjs-api-utils';

...

export default withMiddleware()()(handler);

Configuring Middleware

Body Parser

import { withMiddleware } from '@kienleholdings/nextjs-api-utils';

...

export default withMiddleware({
  bodyParserConfig: ['application/json'] // Only allow application/json to be submitted,
})()(handler);

Body Validator

import { withMiddleware } from '@kienleholdings/nextjs-api-utils';
import * as yup from 'yup';

const postSchema = Yup.object().shape({
  foo: Yup.string().required(),
  bar: Yup.bool().required()
});

...

// This enforces that `foo` is a required string and `bar` is a required boolean. The API will
// return a 422 (unprocessable entity) if the schema is not satisfied
export default withMiddleware({
  bodyValidatorConfig: {
    post: postSchema
  }
})()(handler);

CORS

import { withMiddleware } from '@kienleholdings/nextjs-api-utils';

...

// See https://www.npmjs.com/package/cors for more complete configuration options
export default withMiddleware({
  corsConfig: {
    origin: 'http://example.com',
  }
})()(handler);

Generating OpenAPI Specifications

Any good API needs good documentation, but maintaining one giant OpenAPI specification can be a nightmare for backend developers, especially when mege conflicts are involved. Luckily, the package contains an easy utility that turns json files that live alongside your API endpoints into OpenAPI (or Swagger) specifications! Here's how to do it:

  1. In the root of your API's package, create a new file called openapi-base.json
  2. Populate that file with your OpenAPI spec's info, components, .etc
  3. In the same directory as your API endpoint, create a .json file. As an example, if my endpoint was /api/users and contained a file named users.js, I'd create a file named users.json
  4. In your newly-created file, populate it with OpenAPI definitions for each exposed method
  5. Once you've documented all of your API endpoints, run yarn run generate-openapi-spec

Need your files named something different? Need to pull definitions from a different directory? Run generate-openapi-slec --help for full command info

Not sure how to write OpenAPI definitions? The Swagger Editor and PetStore example are both great places to get started

Local Development

  1. Clone the repo
  2. Open the folder as a container with VSCode
  3. Wait for dependencies to install
  4. Run yarn build
  5. Note the output in ./lib