Skip to content

Commit

Permalink
Forking from koa-api-boilerplate
Browse files Browse the repository at this point in the history
  • Loading branch information
christroutner committed Apr 10, 2020
0 parents commit 498ce4b
Show file tree
Hide file tree
Showing 46 changed files with 15,707 additions and 0 deletions.
30 changes: 30 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# http://editorconfig.org

# A special property that should be specified at the top of the file outside of
# any sections. Set to true to stop .editor config file search on current file
root = true

[*]
# Indentation style
# Possible values - tab, space
indent_style = space

# Indentation size in single-spaced characters
# Possible values - an integer, tab
indent_size = 2

# Line ending file format
# Possible values - lf, crlf, cr
end_of_line = lf

# File character encoding
# Possible values - latin1, utf-8, utf-16be, utf-16le
charset = utf-8

# Denotes whether to trim whitespace at the end of lines
# Possible values - true, false
trim_trailing_whitespace = true

# Denotes whether file should end with a newline
# Possible values - true, false
insert_final_newline = true
10 changes: 10 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "standard",
"env": {
"node": true,
"mocha": true
},
"parserOptions": {
"ecmaVersion": 8
}
}
66 changes: 66 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@


# Created by https://www.gitignore.io/api/node,sublimetext

### Node ###
# Logs
#logs
logs/*.json
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
node_modules

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history


### SublimeText ###
# cache files for sublime text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache

# workspace files are user-specific
*.sublime-workspace

# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
*.sublime-project

# sftp configuration file
sftp-config.json

#Documentation
docs

.nyc_output
coverage
database/
system-user-*.json

!README.md
32 changes: 32 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# This is a node.js v8+ JavaScript project
language: node_js
node_js:
- "10"

# Build on Ubuntu Trusty (14.04)
# https://docs.travis-ci.com/user/reference/trusty/#javascript-and-nodejs-images
dist: xenial
sudo: required

# Use Docker
services:
- docker

before_install:
- ./install-mongo
#- npm install -g mocha

# https://github.com/greenkeeperio/greenkeeper-lockfile/issues/156
install: case $TRAVIS_BRANCH in greenkeeper*) npm i;; *) npm ci;; esac;

script: "npm run test"

# Send coverage data to Coveralls
after_success:
- npm run coverage

deploy:
provider: script
skip_cleanup: true
script:
- npx semantic-release
8 changes: 8 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2016 Adrian Obelmejias <[email protected]> & Chris Troutner <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
112 changes: 112 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# koa-api-boilerplate
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com) [![Coverage Status](https://coveralls.io/repos/github/christroutner/babel-free-koa2-api-boilerplate/badge.svg?branch=unstable)](https://coveralls.io/github/christroutner/babel-free-koa2-api-boilerplate?branch=unstable) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![Greenkeeper badge](https://badges.greenkeeper.io/christroutner/koa-api-boilerplate.svg)](https://greenkeeper.io/)


This repository is a boilerplate for building APIs with
[koa2](https://github.com/koajs/koa/tree/v2.x) and Mongo DB.
This repository was originally forked from Adrian Obelmejias'
[koa-api-boilerplate repository](https://github.com/adrianObel/koa2-api-boilerplate).
It makes the following modifications:

- Removes babel as a dependency. This repository is now naively compatible with
node v8.9 or higher.

- Replaced `bcrypt` dependency with `bcryptjs`. This improves compatibility across
versions of node.js and across OSs.

- Configured for Travis CI (continuous integration), Coveralls (code coverage), Green Keeper (automated dependency management), and Semantic Release (automated versioning).

- 'Production' environment is targeted for packaging as a Docker container.

- 'admin' user type added in addition to standard 'user' type. Allows the creation
of private vs public APIs that only be accessed by an admin. Useful for privileged
commands like updating and deleting other users.

- Winston logging integrated for daily rotated logs and a maximum size of
1 megabyte.

## Features
This project covers basic necessities of most APIs.
* Authentication (passport & jwt)
* Database (mongoose)
* Testing (mocha)
* Doc generation with apidoc
* Linting using standard
* Packaged as a Docker container



## Requirements
* node __^10.15.1__
* npm __^6.7.0__

## Installation
```bash
git clone https://github.com/christroutner/koa-api-boilerplate
cd koa-api-boilerplate
npm install
npm start
```

## Structure
```
├── bin
│ └── server.js # Bootstrapping and entry point
├── config # Server configuration settings
│ ├── env # Environment specific config
│ │ ├── common.js
│ │ ├── development.js
│ │ ├── production.js
│ │ └── test.js
│ ├── index.js # Config entrypoint - exports config according to envionrment and commons
│ └── passport.js # Passportjs config of strategies
|
├── production # Dockerfile for build production container
|
├── src # Source code
│ ├── lib # Business logic libraries
│ ├── modules
│ │ ├── controller.js # Module-specific controllers
│ │ └── router.js # Router definitions for module
│ ├── models # Mongoose models
│ └── middleware # Custom middleware
│ └── validators # Validation middleware
└── test # Unit tests
```

## Usage
* `npm start` Start server on live mode
* `npm run dev` Start server on dev mode with nodemon
* `npm run docs` Generate API documentation
* `npm test` Run mocha tests
* `docker-compose build` Build a 'production' Docker container
* `docker-compose up` Run the docker container

## Documentation
API documentation is written inline and generated by [apidoc](http://apidocjs.com/).

Visit `http://localhost:5000/docs/` to view docs


## Dependencies
* [koa2](https://github.com/koajs/koa/tree/v2.x)
* [koa-router](https://github.com/alexmingoia/koa-router)
* [koa-bodyparser](https://github.com/koajs/bodyparser)
* [koa-generic-session](https://github.com/koajs/generic-session)
* [koa-logger](https://github.com/koajs/logger)
* [MongoDB](http://mongodb.org/)
* [Mongoose](http://mongoosejs.com/)
* [Passport](http://passportjs.org/)
* [Nodemon](http://nodemon.io/)
* [Mocha](https://mochajs.org/)
* [apidoc](http://apidocjs.com/)
* [ESLint](http://eslint.org/)

## IPFS
v2.3.0 uploaded to IPFS:

- Get it: `ipfs get QmUz4b2KwNLNvHZRTYcgrPCuKAhMB73XWN8vY8LLVVEYV1`
- Pin it: `ipfs pin add -r QmUz4b2KwNLNvHZRTYcgrPCuKAhMB73XWN8vY8LLVVEYV1`

## License
MIT
78 changes: 78 additions & 0 deletions bin/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// npm libraries
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const convert = require('koa-convert')
const logger = require('koa-logger')
const mongoose = require('mongoose')
const session = require('koa-generic-session')
const passport = require('koa-passport')
const mount = require('koa-mount')
const serve = require('koa-static')
const cors = require('kcors')

// Local libraries
const config = require('../config') // this first.
const adminLib = require('../src/lib/admin')
const errorMiddleware = require('../src/middleware')
const wlogger = require('../src/lib/wlogger')

async function startServer () {
// Create a Koa instance.
const app = new Koa()
app.keys = [config.session]

// Connect to the Mongo Database.
mongoose.Promise = global.Promise
mongoose.set('useCreateIndex', true) // Stop deprecation warning.
await mongoose.connect(config.database, {
useUnifiedTopology: true,
useNewUrlParser: true
})

// MIDDLEWARE START

app.use(convert(logger()))
app.use(bodyParser())
app.use(session())
app.use(errorMiddleware())

// Used to generate the docs.
app.use(mount('/', serve(`${process.cwd()}/docs`)))

// Mount the page for displaying logs.
app.use(mount('/logs', serve(`${process.cwd()}/config/logs`)))

// User Authentication
require('../config/passport')
app.use(passport.initialize())
app.use(passport.session())

// Custom Middleware Modules
const modules = require('../src/modules')
modules(app)

// Enable CORS for testing
// THIS IS A SECURITY RISK. COMMENT OUT FOR PRODUCTION
app.use(cors({ origin: '*' }))

// MIDDLEWARE END

console.log(`Running server in environment: ${config.env}`)
wlogger.info(`Running server in environment: ${config.env}`)

await app.listen(config.port)
console.log(`Server started on ${config.port}`)

// Create the system admin user.
const success = await adminLib.createSystemUser()
if (success) console.log('System admin user created.')

return app
}
// startServer()

// export default app
// module.exports = app
module.exports = {
startServer
}
9 changes: 9 additions & 0 deletions config/env/common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
This file is used to store unsecure, application-specific data common to all
environments.
*/

module.exports = {
port: process.env.PORT || 5001,
logPass: 'test'
}
12 changes: 12 additions & 0 deletions config/env/development.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
These are the environment settings for the DEVELOPMENT environment.
This is the environment run by default with `npm start` if KOA_ENV is not
specified.
*/

module.exports = {
session: 'secret-boilerplate-token',
token: 'secret-jwt-token',
database: 'mongodb://localhost:27017/koa-server-dev',
env: 'dev'
}
15 changes: 15 additions & 0 deletions config/env/production.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
These are the environment settings for the PRODUCTION environment.
This is the environment run with `npm start` if KOA_ENV=production.
This is the environment run inside the Docker container.
It is assumed the MonogDB Docker container is accessed by port 5555
so as not to conflict with the default host port of 27017 for MongoDB.
*/

module.exports = {
session: 'secret-boilerplate-token',
token: 'secret-jwt-token',
database: 'mongodb://172.17.0.1:5555/koa-server-prod',
env: 'prod'
}
12 changes: 12 additions & 0 deletions config/env/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
These are the environment settings for the TEST environment.
This is the environment run with `npm start` if KOA_ENV=test.
This is the environment run by the test suite.
*/

module.exports = {
session: 'secret-boilerplate-token',
token: 'secret-jwt-token',
database: 'mongodb://localhost:27017/koa-server-test',
env: 'test'
}
Loading

0 comments on commit 498ce4b

Please sign in to comment.