Node.js KOA Framework hands-on and MySQL Operations Guide _node.js

Source: Internet
Author: User

KOA, created by the Express native, is committed to becoming a smaller, more robust, more expressive Web framework. Using KOA to write Web applications, by combining different generator, you can eliminate repetitive and cumbersome callback function nesting and greatly enhance common error handling efficiency. Koa does not bind any middleware in the kernel method, it simply provides a lightweight, elegant library of functions that makes it easy to write WEB applications.

Install KOA
KOA relies on support for generator node environments, which means that the version of node is 0.11.9 or higher, otherwise it cannot be performed.

With NPM:

$ NPM Install KOA

Alternatively, choose to install on the global:

$ NPM Install-g KOA

Example
This is a simple example of a KOA:

var koa = require (' KOA ');
var app = Koa ();

Logger

app.use (function * (next) {
 var start = new Date;
 Yield next;
 var ms = new Date-start;
 Console.log ('%s%s-%s ', This.method, This.url, MS);
};

Response

App.use (function * () {
 this.body = ' Hello world ';
});

App.listen (3000);

Unlike ordinary function, generator functions to function* declaration. Functions that are declared with this keyword support yield. The use and meaning of yield will be mentioned later.

Execute KOA
you need to run KOA in--harmony mode to make it easy to set node as the default startup harmony mode alias:

Alias node= ' node--harmony '

This can be used directly when the relevant JS is executed.

Cascading
This is a more abstract concept. Koa Middleware is cascaded in a very traditional way, which is called cascading here.

In the previous Node development, frequent use of callbacks is not easy to show complex code logic, in Koa, we can write a truly expressive middleware. Compared with the method of implementing middleware with Connect, Koa's approach is not simply to transfer control to one or another middleware until the end of the program, Koa executes the code a bit like a paper clip, the user requests through the middleware, encounters the yield next keyword, is passed to the next compliant routing (downstream), which returns the execution code (upstream) in reverse order when yield next captures less than the next middleware.

The example below shows the Hello world paradigm written using this particular method: At first, the user's request was through X-response-time middleware and logging middleware, which recorded some request details and then "crossed"response middleware once, Final end request, return "hello world".

When the program runs to yield next, the code stream suspends execution of the remainder of the middleware code, switching to the next defined middleware execution code, so that the way to switch control is called downstream, and when no next middleware executes downstream, The code will be executed in reverse order.

var koa = require (' KOA ');
var app = Koa ();

X-response-time
app.use (function * (next) {
 //(1) enters route
 var start = new Date;
 Yield next;
 (5) Enter X-response-time middleware again, record 2 times through this middleware "through" time
 var ms = new Date-start;
 This.set (' x-response-time ', Ms + ' MS ');
 (6) return this.body
});

Logger
app.use (function * (next) {
 //(2) enters logger middleware
 var start = new Date;
 Yield next;
 (4) Enter logger middleware again, record 2 times through this middleware "through" time
 var ms = new Date-start;
 Console.log ('%s%s-%s ', This.method, This.url, MS);
};

Response
App.use (function * () {
 //(3) into the response middleware, not captured to the next conforming middleware, passed to upstream
 this.body = ' Hello world ';
});

App.listen (3000);

In the example code above, the middleware is already marked in the annotation in the order in which it was executed. You can also try to run this example on your own, and print out the output and time consuming of each link.

. middleware1 {/
 /(1) do some stuff
 . middleware2 {//
  (2) does some other stuff
  . middleware3 {
   //(3) NO Next yield!
   This.body = ' Hello World '
  }
  //(4) does some other stuff later
 }
 //(5) does some stuff lastest and return
}

The pseudocode above shows the order in which the middleware is executed, and does it look a bit like the performance of yield when Ruby executes a block of code? Maybe it will help you better understand the way KOA works.

KOA access to MySQL database operations
Implementation Method One (Co-mysql)
MySQL Library is implemented as a callback, and KOA middleware requirements promise form, after searching, found Co-mysql and Mysql-co, the two libraries of ideas, Mysql-co packaging more high, and the use of faster MYSQL2, The co-mysql is simpler, but encapsulates the mysql.query into a promise form. The following is based on Co-mysql

var wrapper = require (' Co-mysql '),
 mysql = require (' mysql ');
var options = {
  host: ' localhost ',
  port:3306,
  database: ' Test ',
  User: ' root ',
  password: ' Rootroo T '
};

var pool = mysql.createpool (options),
 p = wrapper (pool);

...
 var rows = yield p.query (' SELECT 1 ');
 Yield This.render (' index ', {
    title:rows[0].fieldname
  });
...
}) ();

Implementation Method II (PROMISIFY-NODE)
Find the Promisify-node library, you can convert the library as a whole into a promise form, the sample code is as follows:

var promisify = require ("Promisify-node");
var db = promisify ("Mydbhelper");
...
var rows = yield Db.getbyid (' tablename ', {id:1});
  Yield This.render (' index ', {
    title:rows[0].fieldname
  });
...

Implementation Method III (Thunkify, Thunkify-wrap)

Using Thunkify can also complete encapsulation, Thunkify-wrap is an enhanced version of the thunkify, but see that this approach in the future development may be eliminated, the approximate use of the following:

var genify = require (' Thunkify-wrap '). genify;
var db = genify ("Mydbhelper");
...
var rows = yield Db.getbyid (' tablename ', {id:1});
  Yield This.render (' index ', {
    title:rows[0].fieldname
  });
...

Implementation Method IV (direct method)
Direct transformation of the original express under the Code for Promise form, reference to the Co-mysql, and carefully learned promise related knowledge, completed the transformation of the Code, Code and instructions are as follows:
Dbhelper.js

var config = require ('./dbconfig '); var options = {' Host ': Config.db_host, ' Port ': config.db_port, ' database ': config.db_name, ' user ': Config.db_user
, ' Password ': config.db_passwd} var mysql = require (' mysql ');

var pool = mysql.createpool (options);
  Internal to MySQL encapsulation, execute SQL statement function ExecQuery (SQL, values, callback) {var errinfo; Pool.getconnection (function (err, connection) {if (err) {errinfo = ' db-Get database connection Exception!
      ';
    Throw errinfo;
        else {var querys = connection.query (sql, values, function (err, rows) {release (connection);
          if (err) {errinfo = ' db-sql statement execution error: ' + err;
        Callback (ERR);    else {callback (null,rows);
    Note: The first parameter must be null}});
}
  }); function release (connection) {try {connection.release (function (Error) {if (error) {Console.log ( ' db-Shutdown database connection Exception!
      ');
  }
    }); The catch (Err) {}}//external interface returns the Promise function Form Exports.getbyid = function (tablename,ID) {return new Promise (function (resolve, reject) {var values = {Id:id}; var sql = ' select * from??
    Where? ';
      ExecQuery (Sql,[tablename, values], function (err, rows) {if (err) {reject (err);
      }else{resolve (rows);
}
    })
  }); routes/index.js var db = require ("..
/dbhelper ");
  ... var rows = yield Db.getbyid (' tablename ', {id:1});
Yield This.render (' index ', {title:rows[0].fieldname});

 ...

Code
Refer to the Database Operations section of this project, where the project is in continuous development and the database sample is taken from the project.
Https://github.com/zhoutk/koadmin.git

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.