Koajs 2.0: a new generation of a new generation framework

    KoaJS logo“Next generation web framework for node.js” - this is written in the documentation for version 1.0. It sounds good, I add to this that 2 years ago after implementing koa on one of the projects, our programmers got the term “pseudo-synchronous code” (This is when the code looks like synchronous but actually executes asynchronously). What kind of nonsense How it works, I'll tell you under the cut.

    What is KoaJS


    So as not to repeat:

    Using the features of the operation of generators and the yield directive, we can execute Promise or a specially designed thinkify function asynchronously and, after performing the promise / function, return to the point where yield was called to return the result and continue executing the code.

    An example of such a code:
    //...
    let userId = Number(this.request.userId);
    let projects = yield users.getActiveProjectsByUserId(userId); // Например, обращаемся к БД
    for (let project of projects) {
       project.owners = yield projects.getProjectOwnersById(project.id); // Тут тоже обращаемся к БД
    }
    this.body = yield this.render('userProjects', projects); // Тут асихронно рендерим ответ
    //...
    

    Why do I need KoaJS?


    The idea of ​​Koa fits perfectly into the microservices paradigm that I have already implemented in our company for a long time. The core of the framework is minimalistic, the middleware code for koa is read and understood very easily, which is very important for team development. Actively used by the ES2015 features framework, minimal trauma to the psyche of a programmer who previously wrote in PHP (these guys do not like callbacks :)).

    Great, what will surprise KoaJS 2.0?


    What was the foundation of KoaJS, namely the co library built on generators is now removed from the base implementation of Koa 2.

    Let's build Hello world!
    const Koa = require('koa');
    const app = new Koa();
    // response
    app.use(ctx => {
      ctx.body = 'Hello Koa';
    });
    app.listen(3000);
    


    As you can see, there are no generators, but then how can I write the “pseudo-synchronous code” I praised. In the simplest case, you can do with the native code:

    app.use((ctx, next) => {
      const start = new Date();
      return next().then(() => {
        const ms = new Date() - start;
        console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
      });
    });
    

    next is a promise, ctx is the request context.

    In this form, many things cannot be implemented without callbacks, so the authors suggest using the new async / await syncisis, which has not yet become a standard and is not natively supported by NodeJS but has long been implemented in the Babel transporter. It looks like this
    app.use(async (ctx, next) => {
      const start = new Date();
      await next();
      const ms = new Date() - start;
      console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
    });
    


    An option is also provided with an additional connection of the co library and generators:
    app.use(co.wrap(function *(ctx, next) {
      const start = new Date();
      yield next();
      const ms = new Date() - start;
      console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
    }));
    


    Compatible with Koa 1.x


    When I talked about “sawn” generators, I was not entirely accurate. For compatibility, if you arrange middleware in the style of koa 1.0, koa 2.0 will connect it and execute it while the console will have “Koa deprecated Support for generators will be removed in v3 ...” In other words, everything will work before version 3.x.

    Here is an example:
    // Koa will convert
    app.use(function *(next) {
      const start = new Date();
      yield next;
      const ms = new Date() - start;
      console.log(`${this.method} ${this.url} - ${ms}ms`);
    });
    


    You can also convert your existing middleware to 2.0 format yourself using the koa-convert module
    const convert = require('koa-convert');
    app.use(convert(function *(next) {
      const start = new Date();
      yield next;
      const ms = new Date() - start;
      console.log(`${this.method} ${this.url} - ${ms}ms`);
    }));
    


    In this case, there are no warnings on the console, so I recommend that you use just this method of connecting legacy middleware.

    Why upgrade to 2.0


    Of course I can’t say 100%, but six months of stable operation of one of the standard services give me confidence that 2.0 is quite stable.

    I want to have the right to choose how to implement my middleware. Koa 2.0 gives me three ways: native, generators, and async / await

    Koa 2.0 already supports many popular middlewares, and if they don’t, then they work through koa-convert.

    If you are looking at new frameworks right now, try a little bit of code on Koa - I am sure you will not regret that you spend time on this.

    What to see



    Also popular now: