James
James

Reputation: 2860

How to create a middleware in Koa.js using ES6

I am building an application in Koa.JS for the first time after coming from a recent background of using Express.

I am using Babel to transpile the code at runtime whilst developing giving me the beneift of wirting ES6+ code.

I am having issues in Koa defining a middleware that I want to use and store on the ctx object to be used later in my application. I am not sure whereI am going wrong as I am able to do similar in Express (albeing not in ES6 code).

Here is my middleware:

const Config = require('../../Config');

import jwt from 'jsonwebtoken';

const JWTController = () => {
    return {
        async generateToken(tokenVars) {
            const secretKey = Config.auth.secret;
            const claims = {
                sub: tokenVars.userid,
                iss: Config.auth.issuer,
                account: tokenVars.accountId,
                permissions: ''
            };

            let token = await jwt.sign(claims, secretKey);
            return token;
        },

        async decodeClaims(token) {
            const decodedToken = jwt.decode( token, {complete: true} );
            return decodedToken;
        }
    }
};

export default JWTController;

And the section of my app.js entry file where I use the middleware:

});
mongoose.connection.on('error', (err) => {
    console.log(err);
});

app.use(bodyParser());
app.use(serve(appRoot + '/../client'));
app.use(serve(appRoot + '/../client/assets'));

app.use((ctx, next) => {
    ctx.JWTController = JWTController;
    next();
});

Can anyone see why this is not working?

Thanks

Upvotes: 1

Views: 644

Answers (1)

Ossaija Thankgod
Ossaija Thankgod

Reputation: 454

Change your middleware definition to

app.use(async (ctx, next) => {
 ctx.JWTController = JWTController;
 await next();

});

Upvotes: 2

Related Questions