Easily handle field checking in Koa

in javascript | development

I've recently been working on an API project using the fantastic Koa.js and found myself constantly repeating if/else blocks of code to check for the existence of various parameters in a request's JSON body.

To cut down on bulk and increase code reuse, I bundled together all of the common patterns I was using into a single new package, koa-field-checker that will easily allow you to verify the existence of a field in your API request bodies.

Essentially what koa-field-checker does is provide a middleware that you can apply to any route you wish in your application and provide some fields that must be present to allow the request through. koa-field-checker will verify that those fields exist, and otherwise will present the client with an HTTP 401 Bad Request and a nicely formatted JSON error.

To install it, just use Yarn:

yarn add koa-field-checker

Here is an example of how you might use the package:

import Koa from 'koa'
import Router from 'koa-router'
import fields from 'koa-field-checker'

const app = new Koa()
const router = new Router()


router.get('/:id', fields(["username", "password"]), function async (ctx, next) {

koa-field-checker is licensed as Apache 2.0, and can be found on Github. Feel free to use it in your applications, hopefully you find it as helpful as I did!