@atlas.js/koa
Koa.js service and a Middleware hook loader for @atlas.js.
Installation
npm i @atlas.js/koa
Usage
Service
The service configuration allows you to define three things:
import { Atlas } from '@atlas.js/atlas'
import * as Koa from '@atlas.js/koa'
const atlas = new Atlas({
config: {
services: {
http: {
listen: {
port: 3000,
hostname: '127.0.0.1',
},
server: {
timeout: 30000,
},
koa: {
proxy: true,
},
middleware: {
module: 'path/to/middleware',
config: {
bodyparser: {},
}
}
}
}
}
})
atlas.service('http', Koa.Server)
await atlas.start()
atlas.services.http
atlas.services.http.server
Example middleware module
Here is an example middleware module that the service supports.
import forcehttps from './forcehttps'
import routes from './routes'
import notfound from './notfound'
export default {
forcehttps,
routes,
notfound,
}
Accessing the Atlas instance
The Atlas instance can be accessed through ctx.atlas
in middleware or routes.
Here is an example middleware that makes use of the Atlas instance inside the route handler. It returns 400 status code with a custom message when the request is made on an insecure protocol.
export default function mkforcehttps(config) {
return function forcehttps(ctx, next) {
if (ctx.atlas.env === 'production' && !ctx.secure) {
ctx.response.status = 426
ctx.response.set({
Upgrade: 'TLS/1.2, HTTP/1.1',
Connection: 'Upgrade',
})
ctx.response.body = {
message: 'I refuse to talk to you while anyone may be listening.',
}
return
}
await next()
}
}
ContextHook
This hook allows you to extend the Koa context object prototype with custom functions or properties. It might be useful to define response type aliases, such as ctx.ok()
, or ctx.forbidden()
.
ContextHook Dependencies
service:koa
: A Koa service on which to extend the context
const atlas = new Atlas({
config: {
hooks: {
context: {
module: 'server/context',
}
}
}
})
atlas.service('http', Koa.Server)
atlas.hook('context', Koa.ContextHook, {
aliases: {
'service:koa': 'http'
}
})
await atlas.start()
export default {
ok(body = {}) {
this.status = 200
this.body = body
},
forbidden() {
this.status = 403
this.body = {
error: 'Forbidden'
}
}
}
WebsocketHook
This hook extends the Koa instance with websocket protocol support, using koa-websocket.
WebsocketHook Dependencies
service:koa
: A Koa service on which to add the websocket protocol support
const atlas = new Atlas({
config: {
hooks: {
websocket: {
middleware: {
module: 'path/to/websocket/middleware',
config: {}
},
listen: {},
}
}
}
})
Once attached to a Koa servise, the websocket interface is accessible as per the library's definition via koa.ws
, which in Atlas it would be:
atlas.services.http.ws
License
See the LICENSE file for information.