基于eggjs+sequelize+mysql搭建nodejs后台服务

745 阅读4分钟

创建egg后台API服务项目基础环境搭建

  • Sequelize 是一个基于 promise 的 Node.js ORM, 目前支持 PostgresMySQLMariaDBSQLite 以及 Microsoft SQL Server.
  • egg.js 是国内最热门的 node.js 框架之一,不同于 exporess、koa 等基础框架,egg.js 在应用级的提炼封装,使其更贴近业务场景,更快上手。eggjs.org。它的约定优于配置更适合团队开发和公司项目开发。

1、安装egg脚手架

create-egg 可以更加快速的帮你创建项目框架,提高开发效率。

(1)切换镜像

nrm use taobao

如果命令出错,那你需要全局安装一下nrm

npm install -g nrm open@8.4.2 --save
E:\Desktop\fun_clinic>nrm ls
  npm ---------- https://registry.npmjs.org/
  yarn --------- https://registry.yarnpkg.com/
  tencent ------ https://mirrors.cloud.tencent.com/npm/
  cnpm --------- https://r.cnpmjs.org/
* taobao ------- https://registry.npmmirror.com/
  npmMirror ---- https://skimdb.npmjs.com/registry/

E:\Desktop\fun_clinic>nrm use taobao
 SUCCESS  The registry has been changed to 'taobao'.

E:\Desktop\fun_clinic>

(2)全局安装脚手架

npm install create-egg -g

(3)安装vscode拓展

  • Egg.js dev tools

Snipaste_2023-10-19_10-45-02.png

  • eggjs

Snipaste_2023-10-19_10-44-24.png

2、初始化服务

E:\Desktop\fun_clinic>create-egg server

? project name server 
? project description smart medical care
? project author doudou
? cookie security keys 1697209339513_8435

[egg-init] usage:
      - cd E:\Desktop\fun_clinic\server
      - npm install
      - npm start / npm run dev / npm test


E:\Desktop\fun_clinic>cd server

E:\Desktop\fun_clinic\server>pnpm install

dependencies:
+ egg 3.17.5
+ egg-scripts 2.17.0

devDependencies:
+ egg-bin 5.14.2 (6.5.2 is available)
+ egg-ci 2.2.0
+ egg-mock 5.10.8
+ eslint 8.51.0
+ eslint-config-egg 12.3.1 (13.0.0 is available)

Done in 9.1s

E:\Desktop\fun_clinic\server>pnpm dev

2023-10-13 23:04:06,912 INFO 18508 [master] egg started on http://127.0.0.1:7001 (4434ms)
  • 页面展示:

Snipaste_2023-10-13_23-07-32.png

3、sequelize实现数据库配置

数据库迁移就是通过命令行的方式,实现对数据库和数据表的创建、管理、维护

(1)安装相关依赖

pnpm install --save egg-sequelize mysql2

(2)引入egg-sequelize

// plugin.js
exports.sequelize = {
  enable: true,
  package: 'egg-sequelize'
}

(3)在config.default.js配置数据库相关

const { Op, col } = require('sequelize')

// 数据库相关
  config.sequelize = {
    dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
    database: 'fc',
    host: 'localhost',
    port: 3306,
    username: 'root',
    password: '123456',
    // 配置数据库时间为东八区北京时间
    timezone: '+08:00',
    // 使用默认运算符别名
    operatorsAliases: {
      $like: Op.like,
      $not: Op.not,
      $col: col
    },
    define: {
      // model的全局配置
      timestamps: true, // 不添加create,update,delete时间戳
      // 字段生成软删除时间戳 deleted_at
      paranoid: false,
      createdAt: 'created_time',
      updatedAt: 'updated_time',
      // deletedAt: 'deleted_at',
      freezeTableName: true, // 防止修改表名为复数
      underscored: false // 防止驼峰式字段被默认转为下划线
    },
    // 打印日志
    logging: true,
    // 时间格式化
    dialectOptions: {
      // 让读取date类型数据时返回时间戳而不是UTC时间
      dateStrings: true,
      typeCast: true
    },
    // 连接池
    pool: {
      max: 5,
      min: 0,
      idle: 10000
    }
  }

(4)创建数据库fc

C:\Users\doudo>mysql -u root -p
Enter password: ******

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| man                |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
7 rows in set (0.02 sec)

mysql> create database fc;
Query OK, 1 row affected (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| fc                 |
| information_schema |
| man                |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
8 rows in set (0.00 sec)

mysql> use fc;
Database changed
mysql>

4、通过 sequelize-cli 实现数据库迁移

sequelize 提供了sequelize-cli工具来实现Migrations,我们也可以在 egg 项目中引入 sequelize-cli

pnpm install sequelize-cli --save-dev

(1).sequelizerc配置文件

egg 项目中,我们希望将所有数据库 Migrations 相关的内容都放在database目录下,所以我们在项目根目录下新建一个.sequelizerc配置文件

// .sequelizerc
const path = require('path')

module.exports = {
  config: path.join(__dirname, 'database/config.json'),
  'migrations-path': path.join(__dirname, 'database/migrations'),
  'seeders-path': path.join(__dirname, 'database/seeders'),
  'models-path': path.join(__dirname, 'app/model')
}

(2)初始化 Migrations 配置文件和目录

npx sequelize init:config
npx sequelize init:migrations
# npx sequelize init:models

(3)修改database/config.json

命令行执行完后会生成database/config.json文件和database/migrations目录,我们修改一下database/config.json中的内容,将其改成我们项目中使用的数据库配置

{
  "development": {
    "username": "root",
    "password": "123456",
    "database": "fc",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": "123456",
    "database": "fc",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": "123456",
    "database": "fc",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}

(4)创建数据库

npx sequelize db:create

(5)创建数据库迁移表

npx sequelize migration:generate --name=user

(6)定义数据表迁移文件

'use strict'

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    const { INTEGER, STRING, DATE, ENUM, TEXT } = Sequelize
    await queryInterface.createTable('user', {
      id: {
        type: INTEGER(20),
        primaryKey: true,
        autoIncrement: true
      },
      username: {
        type: STRING(30),
        allowNull: false,
        defaultValue: '',
        comment: '用户名',
        unique: true
      },
      password: {
        type: STRING,
        allowNull: false,
        defaultValue: '',
        comment: '密码'
      }
    })
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('user')
  }
}

(7)执行 migrate 进行数据库变更

# 数据库变更
npx sequelize db:migrate

# 如果有问题需要回滚,可以通过 `db:migrate:undo` 回退一个变更
# npx sequelize db:migrate:undo

# 可以通过 `db:migrate:undo:all` 回退到初始状态
# npx sequelize db:migrate:undo:all
  • 效果展示:

Snipaste_2023-10-14_16-16-09.png

5、数据表模型

模型是用来操作数据库的,对数据表进行增删改查

这样,基于eggjs+sequelize+mysql的nodejs后台服务基础配置就搭建的差不多了,后面的数据库操作部分下期继续啦。