安裝依賴
- 安裝依賴
- 數(shù)據(jù)庫配置
- 初始化 Sequelize
- 測試連接
- 定義一個(gè)測試數(shù)據(jù)模型
- 同步數(shù)據(jù)結(jié)構(gòu)到數(shù)據(jù)庫
- 定義 Controller 使用 Model 進(jìn)行操作
- 編寫路由接口
npm install sequelize mysql2 --save
數(shù)據(jù)庫配置
新建 config.js 文件 配置好 mysql 一些基本配置
module.exports = {
environment: 'dev',
database: {
dbName: 'island',
host: 'localhost',
port: 3306,
user: 'root',
password: 'root'
}
}
初始化 Sequelize
const Sequelize = require('sequelize')
const { dbName, host, port, user, password } = require('../config').database
const sequelize = new Sequelize(dbName, user, password, {
port,
host,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
dialectOptions: {
// 字符集
charset: "utf8mb4",
collate: "utf8mb4_unicode_ci",
supportBigNumbers: true,
bigNumberStrings: true
},
timezone: '+08:00' //時(shí)區(qū)轉(zhuǎn)換
})
測試連接
sequelize.authenticate().
then(() => console.log('鏈接正常')).
catch(err => console.log('鏈接失敗', err))
定義一個(gè)測試數(shù)據(jù)模型
const { Model, Sequelize } = require('sequelize')
const { sequelize } = require('../../core/db')
class Test extends Model {
}
Test.init(
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
userName: {
type: Sequelize.STRING,
allowNull: false,
//自定義校驗(yàn)
validate: { min: 1, max: 100 }
},
password: {
type: Sequelize.STRING,
set(val) {
//生成鹽
//const salt = bcryptjs.genSaltSync(10);
//加密密碼
//const pwd = bcryptjs.hashSync(val, salt);
this.setDataValue('password', val + 123)
}
}
},
{
// 不要添加時(shí)間戳屬性 (updatedAt, createdAt)
timestamps: true,
// 不實(shí)際刪除數(shù)據(jù) 而是設(shè)置一個(gè)新 deletedAt 屬性,其值為當(dāng)前日期 timestamps 啟用時(shí)
//paranoid: true,
// 不需要 `createdAt`
createdAt: false,
// 需要 `updatedAt`,但列名為"updateTime"
updatedAt: 'updateTime',
// 自動設(shè)置字段為蛇型命名規(guī)則
underscored: true,
// 定義表名
tableName: 'test',
// 添加注釋
comment: '我是測試表',
sequelize,
// 如果指定的表名稱本就是復(fù)數(shù)形式則不變
freezeTableName: true
}
)
module.exports = Test
其中 primaryKey 為主鍵, 我們設(shè)置 autoIncrement 進(jìn)行自增, Sequelize 默認(rèn)的 createdAt 和 updatedAt 我們可以不顯示 或者進(jìn)行改字段名
同步數(shù)據(jù)結(jié)構(gòu)到數(shù)據(jù)庫
當(dāng)模型定義后,需要在數(shù)據(jù)庫中建立對應(yīng)的數(shù)據(jù)表,這時(shí)候需要做結(jié)構(gòu)的同步,可以使用以下方法進(jìn)行同步:
sequelize.sync()
如果數(shù)據(jù)庫中已經(jīng)存在該模型對應(yīng)的表,則我們可以不進(jìn)行結(jié)構(gòu)同步:
sequelize.sync({
force: false
})
定義 Controller 使用 Model 進(jìn)行操作
新建 TestController.js 文件,我們來編寫一個(gè)簡單的增刪改查 RESTful API 接口
const Test = require('../models/test')
const { Faild } = require('../../core/httpException')
class TestController {
}
新增數(shù)據(jù)
static async add(obj) {
const res = await Test.create(obj)
if (!res) {
throw new Faild('添加失敗')
}
return res
}
修改數(shù)據(jù)
static async update(obj) {
const res = await Test.update(obj, {
where: {
id: obj.id
}
})
if (!res) {
throw new Faild('修改失敗')
}
return res
}
查詢列表
static async findAll(obj) {
et res= await Test.findAll()
if (!res) {
throw new Faild('修改失敗')
}
return res
}
查詢單個(gè)
static async find(id) {
let data = await Test.findByPk(id)
// 或者
// Test.findOne({
// where:{
// id
// }
// })
if (!data) {
throw new Faild('查找失敗')
}
return data
}
刪除數(shù)據(jù)
static async dele(id) {
const res = await Test.destroy({
where: {
id
}
})
if (!res) {
throw new Faild('刪除失敗')
}
return res
}
編寫路由接口
const Router = require("koa-router");
const router = new Router()
const testController = require('../controllers/test')
router.get('/test', async (ctx, next) => {
const data = await testController.findAll(ctx.params.id)
ctx.body = data
})
router.get('/test/:id', async (ctx, next) => {
const data = await testController.find(ctx.params.id)
ctx.body = data
})
router.post('/test', async (ctx, next) => {
const data = await testController.add(ctx.request.body)
})
router.put('/test', async (ctx, next) => {
const data = await testController.update(ctx.request.body)
ctx.body = data
})
router.delete('/test/:id', async (ctx, next) => {
const data = await testController.dele(ctx.params.id)
ctx.body = data
})
module.exports = router
至此,我們利用 Sequelize 完成了一個(gè)簡單的增刪改查