GithubHelp home page GithubHelp logo

posquit0 / koa-rest-api-boilerplate Goto Github PK

View Code? Open in Web Editor NEW
486.0 14.0 81.0 2.66 MB

πŸ’― Boilerplate for Node.js Koa RESTful API application with Docker, Swagger, Jest, CodeCov and CircleCI

Home Page: https://koa-rest-api-boilerplate.js.org

License: MIT License

JavaScript 93.34% Dockerfile 4.98% HCL 0.84% Shell 0.84%
koa koa2 node rest restful api boilerplate template skeleton docker circle-ci circleci swagger pm2

koa-rest-api-boilerplate's Introduction

Koa REST API Boilerplate

Koa REST API Boilerplate

Boilerplate for Node.js Koa RESTful API application with Docker, Swagger, Jest, CodeCov, and Circle CI


Koa REST API Boilerplate is a highly opinionated boilerplate template for building RESTful API application with Koa.

This boilerplate include the following features:

  • Logging to STDOUT/STDERR stream using Pino
  • A super small and optimized Docker image based on Node.js Alpine image
  • Swagger API documentation based on JSDoc
  • Continuous integration and delivery using CircleCI
  • Unit Test and Integration Test along with Test Coverage using Jest testing framework

Getting Started

$ git clone https://github.com/posquit0/koa-rest-api-boilerplate your-project-name
$ cd your-project-name
$ rm -rf .git && git init
$ yarn
$ yarn start

Commands

Run

# Run normally
$ yarn start
# Run the application with nodemon for development
$ yarn dev

Test

# Test
$ yarn test                           # Run all test
$ yarn test:unit                      # Run only unit test
$ yarn test:integration               # Run only integration test
# Test (Watch Mode for development)
$ yarn test:watch                     # Run all test with watch mode
$ yarn test:watch:unit                # Run only unit test with watch mode
$ yarn test:watch:integration         # Run only integration test with watch mode
# Test Coverage
$ yarn test:coverage                  # Calculate the coverage of all test
$ yarn test:coverage:unit             # Calculate the coverage of unit test
$ yarn test:coverage:integration      # Calculate the coverage of integration test
# Test consistent coding style (Lint)
$ yarn lint                           # Lint all sourcecode
$ yarn lint:app                       # Lint app sourcecode
$ yarn lint:test                      # Lint test sourcecode

Archive

$ yarn pack

Test

All test for this boilerplate uses following tools.

Contributing

This project follows the Contributor Covenant Code of Conduct.

Bug Reports & Feature Requests

Please use the issue tracker to report any bugs or ask feature requests.

Self Promotion

Like this project? Please give it a β˜… on GitHub! It helps this project a lot. And if you're feeling especially charitable, follow posquit0 on GitHub.

See Also

  • koa-logging - A middleware that logs request and response with Pino.
  • koa-request-id - A middleware that generates a unique Request ID for every incoming HTTP request.
  • koa-http-client - A middleware that attachs HTTP client to communicate with the context during inter-service communications.

License

Provided under the terms of the MIT License.

Copyright Β© 2017-2019, Byungjin Park.

koa-rest-api-boilerplate's People

Contributors

crobinson42 avatar dependabot[bot] avatar fabiothiroki avatar greenkeeper[bot] avatar posquit0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-rest-api-boilerplate's Issues

An in-range update of husky is breaking the build 🚨

The devDependency husky was updated from 3.0.8 to 3.0.9.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

husky is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… ci/circleci: test: Your tests passed on CircleCI! (Details).
  • ❌ codecov/project: 54.36% (-20.72%) compared to 9e6a345 (Details).
  • βœ… codecov/project/integration: 54.36% remains the same compared to 9e6a345 (Details).
  • βœ… codecov/project/unit: 100% (+76.05%) compared to 9e6a345 (Details).

Commits

The new version differs by 5 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of nodemon is breaking the build 🚨

The devDependency nodemon was updated from 1.18.5 to 1.18.6.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

nodemon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: test: Your tests failed on CircleCI (Details).

Release Notes for v1.18.6

1.18.6 (2018-11-05)

Bug Fixes

Commits

The new version differs by 1 commits.

  • 521eb1e fix: restart on change for non-default signals (#1409) (#1430)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Enhance API health check endpoint

Problem

  • GET /status should check the application condition.

Solutions

  • app should check each external connections including db, cache, mq, grpc, or something else.

Design

Configure CORS origins as runtime configuration

Problem

Security Issues

  • IMPACT: The attacker can build a malicious web page to communicate with API in DMZ.

Solutions

  • Limit Access-Control-Allow-Origin with trust host domains on run-time.

Problem Solving

  • Add run-time configuration for CORS origin setting.
  • Dynamically sent Access-Control-Allow-Origin HTTP response header by translating Origin http request header.
    • Configure a list of cors origin with origins option.
    • The default value is * for convenience.

Example

CORS_ORIGINS=https://posquit0.com,https://staging.posquit0.com

Enhance HTTP request data validation

Problem

  • controller should validate the request body, param, query, header, cookie before processing the business logic.
  • Validation should check the data type, format, ranges and more.

Solutions

Design

4XX Response for Invalid JSON request body

Problem

  • app is respond with 500 server error when ctx.req.body has invalid JSON format for application/json content type.

Solution

  • middleware/error-handler should catch the error from koa-bodyparser. However, koa-bodyparser just throws Error class instance. So, we cannot use instanceof method in middleware.

Routes middleware before errorHandler

app.use(router.routes());

I am new to Koa and may be mistaken, but isn't it a problem to have the "routes" middleware registered into the app after the errorHandler middleware? When writing my routes controller I'm experiencing the fact that the errorHandler doesn't capture the status code when it is changed with ctx.throw(409).

My controller looks like this:

const create = async (ctx, next) => {
  const { body } = ctx.state
  try {
    const user = await repo.create(body)
    const token = await sign(user.id)
    const view = { token, user: views.main(user) }
    sendResponse = success(ctx, 201)
    sendResponse(view)
  } catch (err) {
    ctx.throw(409, 'fail') // not caught in errorHandler
  }
}

The controller is registered into 'koa-router' as follow:

const { create } = require('./controller')
router.post('/', create)

Changing the order in which routes and errorHandlers are registered into koa solves my issue.

An in-range update of lint-staged is breaking the build 🚨

The devDependency lint-staged was updated from 8.2.0 to 8.2.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

lint-staged is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… ci/circleci: test: Your tests passed on CircleCI! (Details).
  • βœ… coverage/coveralls: First build on greenkeeper/lint-staged-8.2.1 at 54.654% (Details).
  • ❌ .github/main.workflow: Workflow Error

Release Notes for v8.2.1

8.2.1 (2019-06-13)

Bug Fixes

  • Override env GIT_DIR variable to resolve to the correct git dir path (#629) (5892455), closes #627
Commits

The new version differs by 2 commits.

  • 5892455 fix: Override env GIT_DIR variable to resolve to the correct git dir path (#629)
  • bffef73 chore: Fix tests on Windows (#604)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of pino is breaking the build 🚨

The dependency pino was updated from 5.12.2 to 5.12.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

pino is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • βœ… ci/circleci: test: Your tests passed on CircleCI! (Details).
  • ❌ .github/main.workflow: Workflow Error

Commits

The new version differs by 2 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of husky is breaking the build 🚨

The devDependency husky was updated from 3.0.0 to 3.0.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

husky is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… ci/circleci: test: Your tests passed on CircleCI! (Details).
  • βœ… codecov/project: 71.37% remains the same compared to 04e4e72 (Details).
  • βœ… codecov/project/integration: 43.89% remains the same compared to 04e4e72 (Details).
  • βœ… codecov/project/unit: 28.24% remains the same compared to 04e4e72 (Details).
  • ❌ .github/main.workflow: Workflow Error

Release Notes for v3.0.1
  • Improve error message if git command fails
Commits

The new version differs by 6 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Hosting the web based documentation

Problem

  • README.md is not good to include more detail content. Hosting web-based documentation can be a good solution. There is no hosting cost if we use static web generator and free hosting provider such as GitHub Pages, Netlify.

Solutions

Static Web Generators

Client-side Rendered

  • docsify
    • Smart full-text search plugin
    • Multiple themes
  • docute
    • Leveraging the power of Markdown and Vue
    • Extensible plugin system, plenty of official and community plugins
  • docusaurus

An in-range update of pino is breaking the build 🚨

The dependency pino was updated from 5.12.6 to 5.13.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

pino is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ ci/circleci: test: Your tests failed on CircleCI (Details).
  • ❌ GitHub Action for Docker: Failed!

Release Notes for v5.13.0
  • Updated to standard v13 (#683)
  • Remove note about fastify v2 and link to right doc (#678)
  • Updated copyright to 2019
  • Fix metadata streams docs links #676
Commits

The new version differs by 8 commits.

  • 560d8bd Bumped v5.13.0.
  • c5c996d Updated to standard v13 (#683)
  • 3c7f301 more careful timestamp extraction (#675)
  • 129be44 Remove note about fastify v2 and link to right doc (#678)
  • 4290e37 Merge pull request #676 from drsherlock/fix-docs-broken-links
  • 1a6515a Fix metadata streams docs links
  • e610f4e readme: note that redaction is not supported in the browser (#671)
  • bcbc397 update to 2019

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Custom Error Handling does not print 'err' (proposed change in detail below)

Context

Main Koa App file (app/index.js) has custom error handling logic where 'error' event listener catches uncaught errors and prints error via Bunyan logger.

Issue

Current logging is as follows, which does NOT print the error!!
logger.error({err , event: 'error'}, 'Unhandled Error has occurred');

Fix

This issue has been reported + closed on the Bunyan Repo issue link

Solution is either of the 2 below

  1. Pass in 'err' as root level to Bunyan
# Before
logger.error({err , event: 'error'}, 'Unhandled Error has occurred');

# After
logger.error(err, 'Unhandled Error has occurred');
  1. Add Bunyan Error Serializer to config to use when creating logger (to achieve same effect as below)
var log = bunyan.createLogger({
    name: 'app',
    serializers: bunyan.stdSerializers
});

Enhance the documentation for application configuration

Problem

  • app is configured with environment variables. Developers can check .env.example file, but there is no detailed information for each environment variables.

Solutions

  1. Add Configurations section on README.md
  2. Add separated CONFIGURATION.md file

yarn test:integration 'No tests found' on Windows

Hi BJ!

Current contents of jest.config.js is below.

testMatch: ['<rootDir>/test/**/?(*.)+(spec|test).js?(x)']

run yarn test:integration command and 'No tests found' message appear like below.

Ξ» yarn test:integration
yarn run v1.13.0
$ npm test -- test/integration

> [email protected] test C:\Users\XXX\Desktop\dev\fbackend
> cross-env NODE_ENV=test jest --no-watchman "test/integration"

No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0

So I changed regex like testMatch: ['<rootDir>/test/**/*.(spec|test).(js|jsx)']

and works well!

> cross-env NODE_ENV=test jest --no-watchman

 PASS  test/integration/home.test.js
  Home
    GET /
      √ <200> should always return with the API server information (34ms)
    GET /spec
      √ <200> should always return API specification in swagger format (7ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.515s
Ran all test suites.

Thanks, Bro~πŸ‘

Unit tests not running

I am creating unit tests in my code and they are not being detected; see attached screenshot
screen shot 2018-06-03 at 10 13 32 am

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.