一、egg 初始化
$ mkdir egg-example
$ cd egg-example
$ npm init egg --type=simple
$ npm i
$ npm run dev
二、egg ts
里面集成了有ts編譯功能
將我們的 js 文件改成 ts
需要將 sequelize 換成 sequelize-typescript
import { Sequelize } from 'sequelize-typescript';
// import * as Sequelize from 'sequelize'
將后續用sequelize-typescript寫的模型類加入到sequlize實例中
import Car from '../app/models/Car';
const db = new Sequelize({
dialect: 'mysql',
operatorsAliases: true, //是否識別字段別名中的下划線
database: 'shaliang',
username: 'root',
password: 'root',
timezone: '+08:00',//更改為北京時區
});
db.addModels([Car]);
運行 npm run dev
訪問頁面 報錯 Please set config.keys first
配置文件 config.default.ts 沒有生成對應的 *.d.ts
添加 tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"strict": true,
"noImplicitAny": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"charset": "utf8",
"allowJs": false,
"pretty": true,
"noEmitOnError": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"strictPropertyInitialization": false,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"inlineSourceMap": true,
"importHelpers": true
},
"exclude": [
"app/public",
"app/web",
"app/views"
]
}
package.json
在刪除 node_modules 重新 運行 npm i
在運行 npm run dev
有index.d.ts就正常了,具體看實際情況
三、egg myspl sequelize
依賴包
npm install --save egg-sequelize mysql2
plugin.ts
config.default.ts
app/model/user.ts
'use strict';
const moment = require('moment');
module.exports = app => {
const { INTEGER, DATE, STRING, ENUM } = app.Sequelize;
const User = app.model.define('user', {
id: { type: INTEGER(11), primaryKey: true, autoIncrement: true },
username: { type: STRING(255), allowNull: false },
password: { type: STRING(255), allowNull: false },
age: { type: ENUM('未知', '男', '女'), defaultValue: '未知', allowNull: false },
created_at: { type: DATE, allowNull: false, get() { return moment((this as any).getDataValue('created_at')).format('YYYY-MM-DD HH:mm:ss'); } },
updated_at: { type: DATE, allowNull: false, get() { return moment((this as any).getDataValue('updated_at')).format('YYYY-MM-DD HH:mm:ss'); } },
}, {
paranoid: false,
timestamps: true,
});
return User;
};
app/controller/user.ts
'use strict';
import { Controller } from "egg";
function toInt(str) {
if (typeof str === 'number') return str;
if (!str) return str;
return parseInt(str, 10) || 0;
}
class UserController extends Controller {
async index() {
const { ctx } = this;
const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };
ctx.body = await ctx.model.User.findAll(query);
}
async show() {
const { ctx } = this;
ctx.body = await ctx.model.User.findByPk(toInt(ctx.params.id));
}
async create() {
const { ctx } = this;
const { username } = ctx.request.body;
const user = await ctx.model.User.create({ username });
ctx.status = 201;
ctx.body = user;
}
async update() {
const { ctx } = this;
const id = toInt(ctx.params.id);
const user = await ctx.model.User.findByPk(id);
if (!user) {
ctx.status = 404;
return;
}
const { username } = ctx.request.body;
await user.update({ username });
ctx.body = user;
}
async destroy() {
const { ctx } = this;
const id = toInt(ctx.params.id);
const user = await ctx.model.User.findByPk(id);
if (!user) {
ctx.status = 404;
return;
}
await user.destroy();
ctx.status = 200;
}
}
module.exports = UserController;
四、sequelize 生成模型 創建數據表
(一)、利用 sequelize-cli 可以快速生成表模型
1、全局安裝
npm install sequelize-cli -g
2、 初始化 項目的數據庫配置信息
npx sequelize init
生成 database/
1.migrate 目錄
2.model 目錄
3.config.json
3、 創建 user 表模型
npx sequelize model:generate --name user --attributes name:string,deadline:date,content:string
4、 根據模型創建數據表
npx sequelize db:migrate
5、 sequelize-cli 配置文件
.sequelizerc
'use strict';
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'),
};
(二)、利用 egg-sequelize-auto 可以快速生成表模型
比較重要的參數說明
Options:
-h, --host [required] * 數據庫地址
-d, --database [required] * 數據庫名稱
-u, --user # 數據庫用戶名
-x, --pass # 數據庫密碼
-p, --port # 數據庫端口號
-c, --config # Sequelize的構造函數“options”標記對象的JSON文件路徑
-o, --output # 輸出文件路徑
-e, --dialect # 數據庫類型:postgres, mysql, sqlite
-a, --additional # 包含在model的配置參數中define的模型定義的JSON文件路徑
-t, --tables # 要導出的表名,多個表名逗號分隔,空值就導出所有表模型
-T, --skip-tables # 要跳過的表名,多個表名逗號分隔
-C, --camel # 使用駝峰命名模型和字段
-n, --no-write # 是否寫入文件
-s, --schema # 從中檢索表的數據庫架構(翻譯不動,也沒明白作用,原文:Database schema from which to retrieve tables)
-z, --typescript # 將模型輸出為typescript文件
1、全局安裝依賴
npm install -g egg-sequelize-auto
npm install -g mysql2
2、生成需要的表結構
egg-sequelize-auto -o "./model" -d databaseName -h localhost -u username -p port -x password -t tableName
3、生成用戶日志表模型
在model中就可以看到生成了一個文件,是針對用戶日志的表的模型userlogs.js
egg-sequelize-auto -o "./model" -h 192.168.0.205 -d digapisids -u root -x MVfagsbHHFQnjUmf# -p 3306 -t userlogs
4、一次性生成所有表結構
egg-sequelize-auto -o "./model" -d digapisids -h 192.168.0.205 -u root -x MVKafZN39QnjUmf# -p 13306 -e mysql
5、命令腳本 sequelize.model.js
'use strict';
// sequelize.model.js
const child_process = require('child_process');
const { exec } = child_process;
const modelName = process.argv[2];
const database = {
// [required] * 數據庫地址
host: 'localhost',
// [required] * 數據庫名稱
database: 'ips',
// 數據庫用戶名
user: 'root',
// 數據庫密碼
pass: '',
// 數據庫端口號
port: 3306,
// Sequelize的構造函數“options”標記對象的JSON文件路徑
config: '',
// 輸出文件路徑
output: './dbModel',
// 數據庫類型:postgres, mysql, sqlite
dialect: 'mysql',
// 包含在model的配置參數中define的模型定義的JSON文件路徑
additional: '',
// 表名,多個表名逗號分隔
tables: modelName || '',
// 要跳過的表名,多個表名逗號分隔
'skip-tables': '',
// 使用駝峰命名模型和字段
camel: true,
// 是否寫入文件
'no-write': false,
// 從中檢索表的數據庫架構
schema: false,
// 將模型輸出為typescript文件
typescript: false,
};
let connectShell = 'sequelize-auto';
for (const i in database) {
const value = database[i];
if (value) {
if (value === true) {
connectShell += ` --${i}`;
} else {
connectShell += ` --${i} ${value}`;
}
}
}
exec(connectShell, (err, stdout, stderr) => {
console.log(`stderr: ${stderr}`);
console.log(`stdout: ${stdout}`);
if (err) {
console.log(`exec error: ${err}`);
}
});
6、package.json
// package.json
{
"scripts": {
"model": "node sequelize.model.js"
}
}
# 把所有表model文件
npm run model
# 把單個對應表名model文件
npm run model user