node.js如何封装一个接口

2023-11-16

用到的应用: 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,打开,即可看到我们封号的接口文档。




 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

node.js如何封装一个接口 的相关文章

随机推荐