NodeJs(express)之ORM组件sequelize
安装依赖包
## 为了方便写API我引入了express
npm i express
npm i sequelize
npm i mysql2
新建appConfig.js用于读取多环境下的配置
const AppConfig = {
nodeEnv: process.env.NODE_ENV,
nodeHost: process.env.SERVER_HOST,
nodePort: process.env.SERVER_PORT,
dbHost: process.env.DB_HOST,
dbName: process.env.DB_NAME,
dbPort: process.env.DB_PORT,
dbUser: process.env.DB_USER,
dbPassword: process.env.DB_PASSWORD,
dbDialect: process.env.DB_DIALECT,
dbPoolMax: parseInt(process.env.DB_POOL_MAX),
dbPoolMin: parseInt(process.env.DB_POOL_MIN),
dbPoolIdle: parseInt(process.env.DB_POOL_IDLE)
};
module.exports = AppConfig
新建db.js用于数据库建立连接
const Sequelize = require('sequelize')
const AppConfig = require('./appConfig')
const sequelize = new Sequelize(AppConfig.dbName, AppConfig.dbUser, AppConfig.dbPassword, {
host: AppConfig.dbHost,
port: AppConfig.dbPort,
dialect: AppConfig.dbDialect,
pool: {
max: AppConfig.dbPoolMax,
min: AppConfig.dbPoolMin,
idle: AppConfig.dbPoolIdle
},
logging: true
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
module.exports = sequelize;
新建数据实体类,此类与数据库表对应
const { Sequelize, Model} = require('sequelize');
const sequelize = require('../db')
class User extends Model {}
User.init({
id : {
type: Sequelize.INTEGER,
field: 'id',
autoIncrement: true,
primaryKey: true,
allowNull: false
},
name: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
age: {
type: Sequelize.INTEGER,
allowNull: false
}
},
{
sequelize: sequelize,
// 数据库表名称
tableName: 'user',
// 不自动生成createdate\update时间字段值
timestamps: false
}
)
module.exports = User
在router文件夹下新建文件userRouter.js,在service文件夹下新建文件userService.js
userRouter.js
const express = require('express')
const urouter = express.Router()
const UserService = require('../service/userService')
urouter.get('/user/:name', async (req, res) => {
console.log('*** ' + req.params.name)
let user = await UserService.getUserByName(req.params.name);
res.send(user)
})
module.exports = urouter
userService.js
const User = require('../model/user')
exports.getUserByName = async name => {
console.log(name);
let user = await User.findOne({
where: {
name: name
},
});
return user;
}
注册路由
index.js
const express = require('express')
const app = express()
const NODE_ENV = process.env.NODE_ENV
const dotenvFile = NODE_ENV? `.env.${NODE_ENV}` : '.env'
require('dotenv').config({path: dotenvFile})
const AppConfig = require('./appConfig')
const Host = AppConfig.nodeHost
const Port = AppConfig.nodePort
const urouter = require('./router/userRouter')
// 注册路由中间件, 并给所有API添加统一前缀 /api
app.use('/api', urouter)
app.listen(Port, () => console.log(`server address: http://${Host}:${Port} !`))
访问接口
http://localhost:3000/api/user/xiao
{
"id": 1,
"name": "xiao",
"password": "123456",
"age": 12
}