Skip to content

Instantly share code, notes, and snippets.

@mhingston
Last active April 9, 2016 11:38
Show Gist options
  • Save mhingston/9c43901e2d4cd2554fb476fcbd2e6ffa to your computer and use it in GitHub Desktop.
Save mhingston/9c43901e2d4cd2554fb476fcbd2e6ffa to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
// Refer to: https://github.com/saadq/koa2-skeleton for more
if(process.env.NODE_ENV === "production")
{
require("newrelic")
}
import {install} from "source-map-support"
install()
import cluster from "cluster"
import os from "os"
import Promise from "bluebird"
import config from "./config/default.json"
import pkg from "./package.json"
import Koa from "koa"
import views from "koa-views"
import helmet from "koa-helmet"
import serve from "koa-static"
import compress from "koa-compress"
import bodyParser from "koa-bodyparser"
import index from "./routes/index"
const app = new Koa()
app.name = pkg.description
app.proxy = true
/* Begin Middleware */
// Error Handler
app.use(async (ctx, next) =>
{
try
{
await next()
}
catch(error)
{
ctx.status = error.status || 500
ctx.body =
{
message: error.showMessage && error.message ? error.message : "Internal Server Error."
}
}
})
// CORS Handler
app.use((ctx, next) =>
{
ctx.set("Access-Control-Allow-Origin", "*")
ctx.set("Access-Control-Allow-Methods", "GET,HEAD,PUT,POST,DELETE")
return Promise.resolve(next())
})
// Secure Headers
app.use(helmet())
// Static Handler
app.use(serve(`./public`))
// Compression Handler
app.use(compress())
// Body Parser Handler
app.use(bodyParser(
{
onerror: (error, ctx) =>
{
ctx.status = 422
ctx.body =
{
message: "Unable to parse request body."
}
}
}))
// Views Handler
app.use(views("./views",
{
map:
{
html: "lodash"
}
}))
/* End Middleware */
/* Begin Routes */
app.use(index.routes())
// 404 Handler
app.use((ctx, next) =>
{
if(ctx.status === 404)
{
ctx.body =
{
message: "Resource Not Found."
}
}
})
// End Routes
// Clustering
if(cluster.isMaster)
{
os.cpus().forEach(() => cluster.fork())
cluster.on("online", worker => console.log(`Worker ${worker.process.pid} online.`))
cluster.on("message", message => console.log(message))
cluster.on("exit", (worker, signal) =>
{
console.log(`Worker ${worker.process.pid} died (signal: ${signal}). Restarting...`)
cluster.fork()
})
}
else
{
app.listen(config.port, () => console.log(`Listening on http://127.0.0.1:${config.port}`))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment