提示:学习express,搭建管理系统
文章目录
- 前言
- 一、新建models/shop.js
- 二、新建routes/shop.js
- 三、修改routes下的index.js
- 四、添加商户
- 总结
前言
需求:主要学习express,所以先写service部分
一、新建models/shop.js
models/shop.js
const query = require('../config/db');
const bcrypt = require('../config/bcrypt');
const md5 = require('md5');
const jwt = require('../config/jwt');
const secretKey = 'longlongago';
const errFun = (msg,code)=>{
return {
code:code||500,
success:false,
msg:msg||'操作失败'
}
}
const sucFun = (data,msg)=>{
return {
code:200,
success:true,
msg:msg||'操作成功',
data,
}
}
const shopDao = {
//注册
addShopByUserId:async(data)=>{
//验证账号密码格式
const validateResult =shopDao.validateShopName(data);
if(!validateResult.success)return errFun(validateResult.msg);
//查询商户名是否已存在
const userResult = await shopDao.queryShopByShopName(data);
if(userResult.success)return errFun('商户名已存在');
//生成shopId
const shopId = md5(data.shopName+secretKey);
//根据shopName查询shop
const sql = `insert into shop (shopId,shopName,createId) values('${shopId}','${data.shopName}','${data.createId}')`;
const result = await query(sql);
if(result&&result.affectedRows==1)return sucFun({},'添加商户成功');
return errFun('添加商户失败');
},
//通过商户名查询商户信息
queryShopByShopName:async(data)=>{
//根据shopName查询shop
const sql = `select * from shop where shopName='${data.shopName}'`;
const result = await query(sql);
if(result&&result.length>0)return sucFun(result[0],'查询商户成功');
return errFun('查询商户失败');
},
//通过商户名查询商户信息
queryShopByShopId:async(data)=>{
//根据shopName查询shop
const sql = `select * from shop where shopName='${data.shopName}'`;
const result = await query(sql);
if(result&&result.length>0)return sucFun(result[0],'查询商户成功');
return errFun('查询商户失败');
},
//验证商户名密码
validateShopName:(data)=>{
//只包含大小写字母数字,包含1种即可
let nameReg = /[\da-zA-z]{6,16}$/;
let nameValidate = nameReg.test(data.shopName);
if(!nameValidate)return errFun('商户名格式错误');
return sucFun({},'商户名格式正确');
},
}
module.exports = shopDao;
二、新建routes/shop.js
routes/shop.js
const shopDao = require('../models/shop');
const shopRoutes = (router)=>{
router.post('/shop/addShopByUserId',async (req,res)=>{
const result = await shopDao.addShopByUserId(req.body);
res.json(result);
});
}
module.exports = shopRoutes;
三、修改routes下的index.js
读取routes文件夹下的所有文件列表,过滤去掉index.js之后,引入并实例化剩余route
一劳永逸,不用每次添加route文件,都得修改index.js文件
const fs = require('fs');
const routes = (router)=>{
const files = fs.readdirSync(__dirname)||[];
files.forEach(item=>{
if(item.indexOf('index')==-1)require(__dirname+'/'+item)(router);
})
}
module.exports = routes;
四、添加商户
url:http://localhost:1990/shop/addShopByUserId
name:/shop/addShopByUserId
params:{
"shopName": "shop01",
"createId": "d9ef196010ee41be28ba70a0f819da9d"
}
params:{
"shopName": "shop01",
"createId": "e9fd658aa2e171a3c145c4586d750b50"
}
总结
踩坑路漫漫长@~@