1. 程式人生 > >node.js如何封裝一個介面

node.js如何封裝一個介面

用到的應用: 1.webstorm  2.Navicat for MySQL 3.postman

一.使用express建立專案

1.

npm install express-generator -g
2.
express myapp

二.使用Navicat for MySQL將mysql表引入,開啟資料庫

三.專案中引入sequlize-auto

參考文件:https://github.com/sequelize/sequelize-auto

1.

npm install -g sequelize-auto
2.建立auto.js
var SequelizeAuto = require('sequelize-auto'
) var auto = new SequelizeAuto( 'hhdj', 'root', 'root', { host: 'localhost', dialect: 'mysql', directory: './models', // prevents the program from writing to disk port: '3306', additional: { timestamps: false //... } } ) auto.run(function (err) { if (err) throw err; console
.log(auto.tables); // table list console.log(auto.foreignKeys); // foreign key list });

執行auto.js 命令: node ./auto.js

此時會在根目錄下建立models資料夾

3.在此資料夾下建立index.js

寫一個模板處理資料庫對映,建create.js 

let fs = require('fs')
let files = fs.readdirSync('./models')
let models = []
// 解析名稱做成駝峰命名法
files.forEach(item => {
    if 
(item != 'index.js') { let names = item.split('.')[0].split('_') let name = '' for (let i = 1; i < names.length; i++) { name += names[i].substring(0,1).toUpperCase() + names[i].substring(1) } models.push({name: name, path: './' + item}) } }) // 檔案內容模板 const template = ` var Sequelize = require('sequelize'); // 建立資料庫連線var sequelize = new Sequelize('hhdj', 'root', 'root', { host: 'localhost', dialect: 'mysql', pool: { max: 5, min: 0, idle: 10000 } }) // 資料庫模型名稱及lujing const models =${JSON.stringify(models, null, 4)}// 資料模型輸出models.forEach(item => { module.exports[item.name] = require(item.path)(sequelize, Sequelize) }) ` fs.writeFile("./models/index.js", template, function () { console.log('建立成功') })
執行: node ./create.js,

此時可在index.js中看到:

var  Sequelize = require('sequelize');
// 建立資料庫連線
var sequelize = new Sequelize('hhdj', 'root', 'root', {
    host: 'localhost',
dialect: 'mysql',
pool: {
        max: 5,
min: 0,
idle: 10000
}
})
// 資料庫模型名稱及lujing
const models =[
    {
        "name": "ApplyInfo",
"path": "./tb_apply_info.js"
},
{
        "name": "Branch",
"path": "./tb_branch.js"
},
{
        "name": "Carousel",
"path": "./tb_carousel.js"
},
{
        "name": "Comment",
"path": "./tb_comment.js"
},
{
        "name": "CommentRelation",
"path": "./tb_comment_relation.js"
},
{
        "name": "CommentUser",
"path": "./tb_comment_user.js"
},
{
        "name": "Coordinate",
"path": "./tb_coordinate.js"
},
{
        "name": "Forum",
"path": "./tb_forum.js"
},
{
        "name": "ForumComment",
"path": "./tb_forum_comment.js"
},
{
        "name": "Impress",
"path": "./tb_impress.js"
},
{
        "name": "Integral",
"path": "./tb_integral.js"
},
{
        "name": "IntegralRule",
"path": "./tb_integral_rule.js"
},
{
        "name": "News",
"path": "./tb_news.js"
},
{
        "name": "Notice",
"path": "./tb_notice.js"
},
{
        "name": "PartyStyle",
"path": "./tb_party_style.js"
},
{
        "name": "Payfee",
"path": "./tb_payfee.js"
},
{
        "name": "Picture",
"path": "./tb_picture.js"
},
{
        "name": "Report",
"path": "./tb_report.js"
},
{
        "name": "StudyFile",
"path": "./tb_study_file.js"
},
{
        "name": "User",
"path": "./tb_user.js"
},
{
        "name": "Manager",
"path": "./user_manager.js"
}
]
// 資料模型輸出
models.forEach(item => {
    module.exports[item.name] = require(item.path)(sequelize, Sequelize)
})

到此資料庫部分寫完了。

四。在routes資料夾下建立api資料夾,index.js

1.封裝一個登陸介面。

  a,先寫一個util.js處理介面格式與檢查token

var jwt = require('jwt-simple')
var User = require('../models').User
module.exports = function () {
    // 檢查token
this.checkToken = (req, res, next) => {
        var t = req.headers['access-token']
        if (!t) {
            res.send(this.setResult(300, 'no token'))
            return
}
        var token = jwt.decode(t, 'hhdjj')
        User.find({where: {id: token.id}})
            .then(r =>{
                req.TOKEN_USER = r
                next()
            })
            .catch(r => {
                res.send(this.setResult(300, 'token驗證失敗'))
            })
    }
    // 設定token
this.setToken = (obj) => {
        return jwt.encode(obj, 'hhdjj')
    }
    // 介面統一返回格式
this.setResult = (code, message='success', data = null) => {
        return {
            code: code,
message: message,
data: data
        }
    }
}
b,在index.js寫入
const express = require('express')
const router =express.Router()
var Util = require('./util')
var a =new Util()
var crypto = require('crypto') // 用於密碼加密
var User = require('../models').User

router.post('/user/login',function(req, res, next) {
    var phone = req.body.phone
var password = req.body.password
    if (!phone) {
        res.send(a.setResult(301, '賬號空'))
        return
}
    if (!password) {
        res.send(a.setResult(301, '賬號空'))
        return
}
    var md5 = crypto.createHash('md5') // md5加密
var upPassword = password + 'hhdj'
var params = {
        where: {
            password: md5.update(upPassword).digest('hex'),
phone: phone
}
    }
    User.findOne(params)
        .then( su => {
            res.send(a.setResult(200, 'success', a.setToken(su)))
            }
        )
        .catch( ex => {
                // res.send({code: 500, message: 'error'})
res.send(a.setResult(500, 'error'))
            }
        )
)
module.exports = router
c.此時執行專案並使用postman除錯。

五,使用apidoc寫介面文件

介面文件:http://apidocjs.com/#demo

先下載 : npm install apidoc --save 

在上面的index.js寫入

/**
 * @api {post} /user/login Request User information
 * @apiName 登入
* @apiGroup User
 *
 * @apiParam {String} phone 手機號.
 * @apiParam {String} password 密碼
*
 * @apiSuccess {String} code 200 of the User.
 * @apiSuccess {String} message  success of the User.
 * @apiSuccess {String} data 資料 of the User
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       'code': 200,
 *       'message': 'success',
 *       'data': su
 *     }
 *
 * @apiError UserNotFound The id of the User was not found.
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *       'code': 500,
 *       'message': 'error'
 *     }
 */

在文件根目錄下建立apidoc.json,寫入

{
  "name": "name",
"version": "1.0.0",
"description": "apiDoc basic example",
"title": "title",
"url" : "localhost:3000"
}
執行 

apidoc -i routes/api/ -o apidoc/

此時會生成一個apidoc的資料夾,下面有個index.html,開啟,即可看到我們封號的介面文件。