Search code examples
javascriptnode.jsecmascript-6koa

Calling an ES6 class middleware using KOA


I have a function in an ES6 class that i'm trying to call as a middleware but to no success. In my index file, i have:

*I have only included relevant code

"use strict";
    const http        = require('http')
    const Koa         = require('koa')
    const app         = new Koa()
    const bodyParser  = require('koa-better-body')
    const Install     = require('./.system/install/install')   
    const install     = new Install()

class index {
  /**
  * Class constructor function
  * @Class Index
  * @method constructor
  * @return {undefined}
  */
  constructor () {
  }

  /**
  * Main entry method 
  * @Class Index
  * @method init async
  * @return {undefined}
  */
  async init(){
    // install helper
    app.use(install.setup)

    // response
    app.use(async ctx => {
      ctx.body = 'Hello World';
    });

    http.createServer(app.callback()).listen(8080);
  }
}

let init = new index(); init.init()

And in my install.js, I have:

       "use strict";
        const process = require('./library/process')
        const fs      = require('async-file')

    module.exports = class install {
        async setup (ctx, next) { 
            ctx.body = 'install';
        }
    }

But the koa app keeps giving me a 404 not found error. I know a static method might solve this but i'd rather not use static methods. The install class has both a middleware function and standard functions.


Solution

  • You have 404, because you don't use koa-router