Skip to content

Commit

Permalink
Handler instance per request
Browse files Browse the repository at this point in the history
  • Loading branch information
heynemann committed Nov 8, 2016
1 parent e5c9845 commit 90b4202
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ run: _run-app
# test your application (tests in the test/ directory)
test: _services _drop-test _db-test _test-unit

unit: _drop-test _db-test _test-unit-fast

test-watch: _services
@env ALLOW_CONFIG_MUTATIONS=true ./node_modules/mocha/bin/mocha --watch --require babel-polyfill --compilers js:babel-core/register 'test/**/*Test.js'

Expand Down
30 changes: 18 additions & 12 deletions src/api/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { connect as pgConnect } from '../extensions/postgresql'
import { connect as kafkaClientConnect } from '../extensions/kafkaClient'
import { connect as kafkaProducerConnect } from '../extensions/kafkaProducer'

process.setMaxListeners(50)

export default class MarathonApp {
constructor(config) {
Expand All @@ -27,14 +28,13 @@ export default class MarathonApp {
this.pgConfig = config.get('app.services.postgresql')
}

getHandlers() {
const self = this
getHandlers() { //eslint-disable-line
const handlers = []

// Include handlers here
handlers.push(new HealthcheckHandler(self))
handlers.push(new AppsHandler(self))
handlers.push(new AppHandler(self))
handlers.push(HealthcheckHandler)
handlers.push(AppsHandler)
handlers.push(AppHandler)

return handlers
}
Expand Down Expand Up @@ -126,22 +126,28 @@ export default class MarathonApp {
}

async initializeApp() {
const self = this
await this.initializeServices()
const router = koaRouter()
this.handlers.forEach((handler) => {
this.handlers.forEach((HandlerClass) => {
const inst = new HandlerClass(self)
this.allowedMethods.forEach((methodName) => {
if (!handler[methodName]) {
if (!inst[methodName]) {
return
}
const handlerMethod = handler[methodName].bind(handler)
const handlerMethod = inst[methodName]
const method = router[methodName]
const args = [handler.route]
const args = [inst.route]
const validateName = camelize(`validate_${methodName}`)
if (handler[validateName]) {
args.push(handler[validateName].bind(handler))
if (inst[validateName]) {
args.push(async (ctx, next) => {
const handlerInstance = new HandlerClass(self)
await handlerInstance[validateName].bind(handlerInstance)(ctx, next)
})
}
args.push(async (ctx) => {
await handlerMethod.apply(handler, [ctx])
const handlerInstance = new HandlerClass(self)
await handlerMethod.apply(handlerInstance, [ctx])
})
method.apply(router, args)
})
Expand Down

0 comments on commit 90b4202

Please sign in to comment.