node + express + sequelize + apidoc 后台初始化

技术栈:express-generator + sequelize + apidoc

一、创建应用骨架:

express官网

1. 创建文件夹,名称为:express
2. cd到express文件夹,运行Express应用程序生成器

npx express-generator

3. 安装依赖包

npm install

4. 启动应用

set DEBUG=express:* & npm start

或者

npm start

5. 查看应用

浏览器打开:localhost:3000
二、安装常用插件

1. nodemon,热更新
修改package.json启动命令,采用nodemon启动项目

"scripts": {
    "start": "nodemon ./bin/www"
},

2. 数据库

  • 电脑安装mysql
    运行mysql,并使用navicat连接

参考地址

  • 数据库依赖
    sequelize:一个基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server. 它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能。
    sequelize官网
    mysql2
  • 连接数据库
    根目录下新建db.js
const Sequelize = require('sequelize')

const sequelize = new Sequelize(数据库名称, 数据库账户, 数据库密码, {
    host: 'localhost',
    port: '3306',
    dialect: 'mysql',
    define: {
        // 全局禁用时间戳,不然数据表里需要创建时间戳列;或者每次创建表时单独禁用或创建时间戳列。否则会报错。
        timestamps: false
    }
})

sequelize.authenticate().then(() => {
    console.log('database connection has been established successfully.')
}).catch(err => {
    console.log('unable to connect to the database', err)
})

module.exports = sequelize

根目录下新建models文件夹,然后在models文件夹下新建user.js文件

const Sequelize = require('sequelize')
const sequelize = require('../db')
const db = require('../db')

// 模型定义
const User = db.define('User', {
    id: {
        type: Sequelize.INTEGER(11),
        primaryKey: true
    },
    username: {
        type: Sequelize.STRING(0)
    },
    password: {
        type: Sequelize.STRING(12)
    }
})

// 模型同步
// 立即执行函数如果报错,加上分号再试
; (async () => {
    // User.sync() - 如果表不存在,则创建该表(如果已经存在,则不执行任何操作)
    await User.sync()
})();


module.exports = User

修改routes文件夹下的user.js文件

var express = require('express');
var router = express.Router();

const User = require('../models/user')

/**
@api {get} /user/:id Request User information
 * 
@apiName GetUser
 * 
@apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "firstname": "John",
 *       "lastname": "Doe"
 *     }
 *
 * @apiError UserNotFound The 
id of the User was not found.
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *       "error": "UserNotFound"
 *     }
 */

/* GET users listing. */
router.get('/', async function(req, res, next) {
  const data = await User.findAll()
  res.send({
    data
  });
});

router.get('/add', async function(req, res, next) {
  const oldData = await User.findAll()
  const len = oldData.length
  const user = await User.create({
    id: len,
    username: `user_${len}`,
    password: `password_${len}`
  })
  const data = await User.findAll()
  res.send({
    data
  });
});

module.exports = router;

3. 接口文档
apidoc
apidoc官网
项目根目录下添加apidoc.json文件,这个文件主要包含一些项目的描述信息,例如标题、介绍、版本等。

{
    "name": "example",
    "version": "0.1.0",
    "description": "apiDoc basic example",
    "title": "Custom apiDoc browser title",
    "url": "https://api.github.com/v1"
}

在代码注释里加入apidoc的注解。apidoc不在乎把注释写在哪里,不过还是推荐写在接口所在位置。
上一步:修改routes文件夹下的user.js文件,已加入注释代码。

/**
@api {get} /user/:id Request User information
 * 
@apiName GetUser
 * 
@apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "firstname": "John",
 *       "lastname": "Doe"
 *     }
 *
 * @apiError UserNotFound The 
id of the User was not found.
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *       "error": "UserNotFound"
 *     }
 */

常用的一些注解如下:
apidoc仅解析含有@api或者@apiDefine的注释块。
@apiDefine一个注释块中仅能有一个,@apiDefine可以定义一些通用的内容,比如通用的请求参数,返回值,错误列表等 。
@api 用来定义一个api,需要注意的是,@apiGroup和@apiName是必须的,@apiGroup定义的是左侧导航,@apiName 会拼接到访问路径中。@apiGroup不支持中文,需要和@apiDefine配合使用。

@api 定义API的请求方法、路径和名字
@apiDescription 定义API的描述
@apiGroup 定义API的分组
@apiParam 定义API的参数
@apiParamExample 参数请求的事例
@apiVersion 版本
@apiErrorExample API错误示例
@apiSuccessExample API正常示例

项目根目录下执行:

apidoc -i ./ -o apidoc
  • i 是输入源, -i ./ 表示 要生成apidoc接口文档的项目目录就是当前目录
  • o 是输出 ,-o apidoc 表示当前目录下apidoc 是接口文档的输出目录
    输入输出目录 根据自己需求更改。
    生成的apidoc目录下,包含了所有接口注释信息,浏览器打开文件夹下index.html,即可看见接口文档。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅花三

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值