Hapi+mysql Project actual Combat database operation (IV)

Source: Internet
Author: User

    • Database access

Here's an ORM framework for node sequelize to operate the database, for example MySQL.

To configure database connection information config/db_config.js:

1 // Db_config.js 2 module.exports = {3     database: ' H_api ',// library name 4     Username: ' Root ',// username 5     Password: ' 123456 ',// password  6     Host: ' localhost ',// database address 7     dialect: ' mysql '//  Database type 8 }

Define user model file Modes/user.js, table mappings

//User.jsModule.exports =function(Sequelize, datatypes) {varuser = Sequelize.define ("User", {id:{Type:DataTypes.INTEGER, PrimaryKey:true, Allownull:false, AutoIncrement:true,}, Name:DataTypes.STRING, Sex:DataTypes.BIGINT, Age:DataTypes.INTEGER,},{fr Eezetablename:true,//the model corresponding table name is the same as the modelTimestamps:false    }); returnUser;};

Create a Sequelize object instance, connect to the database Models/index.js the new code is as follows:

//Index.jsConst FS = require ("FS"); Const Path= Require ("path"); Const Sequelize= Require ("Sequelize"); Const Config= require ('.. /config/db_config '); let DB= {};//Create a Sequelize object instance to connect to the databaseLet sequelize =Newsequelize (Config.database, Config.username, Config.password, {host:Config.host, Dialect:Config.dialect, p Ool: {max:5, min:0, Idle:30000    }}); Fs.readdirsync (__dirname). Filter (function(file) {return(File.indexof (".")!== 0) && (file!== "Index.js");}). ForEach (function(file) {varModel = sequelize["Import"] (Path.join (__dirname, file)); Db[model.name]=model;}); Db.sequelize=Sequelize;module.exports= DB;

Configure server.js with the following code:

//Server.jsConst Models=require ('./models '));//Connect DatabasevarInitdb =function(){    varSequelize =models.sequelize; //determine if the database connection is successfulSequelize.sync ({force:false}). Then (function() {Console.log ("Connection Database Successed"); }).Catch(function(Err) {Console.log ("Connection failed due to error:%s", err);    }); }; Initdb ();

After the configuration database is complete, use this instance in routing handler

Under the Routes folder, create a new login.js with the following code:

// login.jsConst JOI = require (' Joi '= require (' ... /controllers '= {    ' get ',    '/login ',    = login;

The Controllers folder creates a new Index.js, iterates through the specified directories, require () each file, and returns a hash structure containing the nested hashes of these modules, as shown in the code below

// index.jsConst Requiredirectory = require (' require-directory '= requiredirectory (module);

Controllers folder new User.js, database operations

//User.jsLet Models = require ('.. /models ') Module.exports={login:function(Request, reply) {returnModels.user.findAll ({where: {name:request.query.name}}). Then (function(Result) {Let reponsemess= {}; if(Result!==NULL) {reponsemess={code:100, message:' Success ', Data:result}} Else{reponsemess={code:-100, message:' Fail ', Data:‘‘                }            }            returnreponsemess;    }); }};

The usual, configure routing

Input address: http://localhost:8090/login?name=1, the database has added a name=1 record

Output: JSON

// module.exports = [    // require (__dirname + '/hello.js '),    // require (__dirname + '/staticfile.js '),    Require (__dirname + '/login.js ')//];

Hapi+mysql Project actual Combat database operation (IV)

Related Article

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.