Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions templates/koa/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
108 changes: 108 additions & 0 deletions templates/koa/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

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

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

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

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

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

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Project specific ignores
bin/
temp/
21 changes: 21 additions & 0 deletions templates/koa/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# MIT License

Copyright (c) 2022 Nicholai Nissen and nodeiflux

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.
11 changes: 11 additions & 0 deletions templates/koa/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Koa template

## Usage

Install:

`npm i`

Develop:

`npm run dev`
15 changes: 15 additions & 0 deletions templates/koa/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { routes } = require ('./routes')

/**
* Create and mount the application
* This composes business logic
*
* @param {import('koa')} app
*/
function mountApp (app) {
app.use(routes.middleware())
}

module.exports = {
mountApp
}
11 changes: 11 additions & 0 deletions templates/koa/controllers/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
*
* @param {import('koa').Context} ctx
*/
async function listAll (ctx) {
ctx.body = 'Hello'
}

module.exports = {
listAll
}
28 changes: 28 additions & 0 deletions templates/koa/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict'

const { createServer } = require('./lib/server')
const { env } = require('./lib/env')
const { mountApp } = require('./app')
const { name } = require('./package.json')

const logger = require('pino')({
level: env.LOG_LEVEL
})

async function main () {
const server = createServer({
logger,
isDev: env.NODE_ENV === 'development'
})

mountApp(server)

server.listen(env.PORT, () => {
logger.info({ name }, `Listening on port ${env.PORT}`)
})
}

main().catch(error => {
logger.fatal({ name, err: error })
process.exit(1)
})
22 changes: 22 additions & 0 deletions templates/koa/lib/env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict'

const { load } = require('ts-dotenv')
const { string } = require('yargs')

const env = load({
PORT: {
type: Number,
default: 3000
},
NODE_ENV: {
type: ['development', 'production'],
default: 'development'
},
LOG_LEVEL: {
type: ['silent', 'trace', 'debug', 'info', 'warn', 'error', 'fatal'],
default: 'info'
},
MONGO_URI: String
})

module.exports = { env }
36 changes: 36 additions & 0 deletions templates/koa/lib/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict'

const Koa = require('koa')
const json = require('koa-json')

const { createLogMw } = require('../middlewares/logger')
const { handleErrors, pageNotFound } = require('../middlewares/errors')

/**
* Create Koa HTTP server
*
* @param {({
* logger?: import('pino').Logger,
* isDev?: boolean
* })} dependencies
*
* @returns {Koa} Koa server
*/
function createServer ({
logger,
isDev
} = {}) {
const server = new Koa()
server.use(json({ pretty: isDev, param: 'pretty' }))
server.use(createLogMw(logger))
server.use(handleErrors)
server.use(pageNotFound)
/* toggle this to silence Koa */
//server.silent = true

return server
}

module.exports = {
createServer
}
51 changes: 51 additions & 0 deletions templates/koa/middlewares/errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const {
isClientError,
isServerError,
NotFound,
} = require('@curveball/http-errors')
const { parseError } = require('../util/errors')

/** @typedef {import('koa').Context} Context */

/**
*
* @param {Context} ctx
* @param {import('koa').Next} next
*/
async function handleErrors (ctx, next) {
try {
await next()
} catch (err) {
const error = parseError(err)
error.instance = ctx.url

if (isServerError(error)) ctx.log.error(error)
if (isClientError(error)) ctx.log.trace(error)

/* propagte error to logger */
ctx.state.error = error

ctx.status = error.httpStatus
ctx.body = {
title: error.title,
httpStatus: error.httpStatus,
instance: error.instance,
detail: error.detail
}
ctx.set('Content-Type', 'application/problem+json; charset=utf-8')
}
}

/**
*
* @param {Context} ctx
*/
async function pageNotFound (ctx, next) {
await next()
if (!ctx.body) ctx.throw(new NotFound(`${ctx.url} was not found`))
}

module.exports = {
handleErrors,
pageNotFound
}
Loading