注意,前情提示:
本代码基于《Node.js(nodejs)对本地JSON文件进行增、删、改、查操作(轻车熟路)》
在/api/demo/文件夹下面创建CURD.base.js
代码内容
const $g = global.SG.$g, fs = global.SG.fs, router = global.SG.router;
module.exports = global.SG.router;
//经常需要修改的内容----------------------------------------------------------------
const demoJsonPath = "json/demo/test.json";//测试存储数据的json文件路径
const apiPath = "/demo/CURD.base";//定义前端请求的接口路径
//----------------------------------------------------------------
const mkdirs = $g.dir.mkdirsByFilePath;//递归创建文件夹目录(基于文件路径)
/**【增】方法➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕➕*/
const __C = (_curd) => {
_curd._doText = "添加";
let jsonPath = _curd.jsonPath, body = _curd.body, success = _response.success, fail = _response.fail;
body = Object.assign({id: $g.date.timestamp()}, body);//自动添加时间戳为id
fs.readFile(jsonPath, (err, data) => {
if (err) return fail && fail({code: -1, msg: "读取数据失败", data: err}, _curd), console.error($g.date.nowtime() + "\n", err, "\n----添加失败----");
data = JSON.parse(data.toString());
data.push(body);
fs.writeFile(jsonPath, JSON.stringify(data), err => {
if (err) return fail && fail({code: -1, msg: "写入数据失败", data: err}, _curd), console.error($g.date.nowtime() + "\n", err, "\n----添加失败----");
success && success({change: body, data}, _curd);//回显发生改变的内容用于关联表处理的前端业务,_curd._doText逻辑
console.log($g.date.nowtime() + "\n", data, "\n----添加成功----");
});
});
};
/**【删】方法✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖*/
const __D = (_curd) => {
_curd._doText = "删除";
const jsonPath = _curd.jsonPath, body = _curd.body, success = _response.success, fail = _response.fail;
const ids = Array.isArray(body.id) ? body.id : [body.id.toString()]; //批量删除功能
fs.readFile(jsonPath, (err, data) => {
if (err) return fail && fail({code: -1, msg: "读取数据失败", data: err}, _curd), console.error($g.date.nowtime() + "\n", err, "\n----删除失败----");
data = JSON.parse(data.toString());
let arr = data, re = [], successIds = [], changes = [];
for (let i = 0, len = arr.length; i < len; i++) {
let a = arr[i];
ids.includes((a.id || "null").toString()) ? (successIds.push(a.id), changes.push(a)) : re.push(a);
}
if (!successIds.length) return fail && fail({code: -1, msg: `没有找到对应id:${ids}的记录,删除失败`, data}, _curd), console.error($g.date.nowtime(), "\n----删除失败----");
fs.writeFile(jsonPath, JSON.stringify(re), err => {
if (err) return fail && fail({code: -1, msg: "写入数据失败", data: err}, _curd), console.error($g.date.nowtime() + "\n", err, "\n----删除失败----");
success && success({change: changes, data: re}, _curd);//回显发生改变的内容用于关联表处理的前端业务,_curd._doText逻辑
console.log($g.date.nowtime() + "\n", re, `\n----id:${successIds}删除成功----`);
});
});
};
/**【改】方法🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧🔧*/
const __U = (_curd) => {
_curd._doText = "修改";
const jsonPath = _curd.jsonPath, body = _curd.body, success = _response.success, fail = _response.fail, id = body.id;
delete body.id;
fs.readFile(jsonPath, (err, data) => {
if (err) return fail && fail({code: -1, msg: "读取数据失败", data: err}, _curd), console.error($g.date.nowtime() + "\n", err, "\n----修改失败----");
data = JSON.parse(data.toString());
let change = null, arr = data;
for (let i = 0, len = arr.length; i < len; i++) {
let a = arr[i];
if (a.id === id) {
for (let key in body) a[key] = body[key];
change = a;
break;
}
}
if (!change) return fail && fail({code: -1, msg: `没有找到对应${id}的记录,修改失败`, data}, _curd), console.error($g.date.nowtime(), "\n----修改失败----");
fs.writeFile(jsonPath, JSON.stringify(data), err => {
if (err) return fail && fail({code: -1, msg: "写入数据失败", data: err}, _curd), console.error($g.date.nowtime() + "\n", err, "\n----修改失败----");
success && success({change, data}, _curd);//回显发生改变的内容用于关联表处理的前端业务,_curd._doText逻辑
console.log($g.date.nowtime() + "\n", data, `\n----id:${id}修改成功----`);
});
});
};
/**【查】方法🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍🔍*/
const __isMatch = (record, obj) => {
let countDefault = 0, countMatch = 0;
for (let key in obj) {
countDefault++;
record[key] == obj[key] && (countMatch++);
}
return countDefault === countMatch;
};
const __R = (_curd) => {
_curd._doText = "查询";
const maxPageSize = 999999999;
const jsonPath = _curd.jsonPath, body = _curd.body, success = _response.success, fail = _response.fail;
let pageNum = parseInt(body.pageNum || 0);//默认从第1页开始
pageNum < 0 && (pageNum = 0);
let pageSize = parseInt(body.pageSize || maxPageSize);//不传参就显示所有数据
pageSize < 0 && (pageSize = maxPageSize);
delete body.pageNum;
delete body.pageSize;
fs.readFile(jsonPath, (err, data) => {
if (err) return fail && fail({code: -1, msg: "读取数据失败", data: err}, _curd), console.error($g.date.nowtime() + "\n", err, "\n----查询失败----");
data = JSON.parse(data.toString());
let re = [];
CURD.js;
let arr = data;
for (let i = 0, len = arr.length; i < len; i++) {
let a = arr[i];
__isMatch(a, body) && re.push(a);
}
re = re.slice(pageNum * pageSize, pageSize ? (pageNum + 1) * pageSize : re.length);
success && success({data: re, total: arr.length, pageNum: pageNum, pageSize: pageSize}, _curd);
console.log($g.date.nowtime() + "\n", re, "\n----查询成功----");
});
};
/**【响应体】方法◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆*/
const _response = {
success: (data, _curd) => $g.json.res(_curd.req, _curd.res, _curd._doText + "成功", data, true),
fail: (err, _curd) => $g.json.res(_curd.req, _curd.res, err.msg, err.data, false)
};
/**【增删改查】方法◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆*/
const CURD = (_curd) => {
//【增】❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤
if ($g.CURD.hasAndNoHasFields(_curd.body, [], ["id", "pageNum", "pageSize"])) return __C(_curd);
//【删】❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤
if ($g.CURD.hasAndNoHasFields(_curd.body, ["id"])) return __D(_curd);
//【改】❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤
if ($g.CURD.hasAndNoHasFields(_curd.body, ["id"], ["pageNum", "pageSize"]) && $g.CURD.hasExceptFields(_curd.body, ["id", "pageNum", "pageSize"])) return __U(_curd);
//【查】❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤
return __R(_curd);
};
/**增删改查数据(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆*/
router.all(apiPath, (req, res) => {
let body = JSON.parse(JSON.stringify(req.body));
let jsonPath = body.jsonPath;//指定存储数据的json文件路径(路径自动添加,如果没有该文件,系统会自动创建此json,业务重心转嫁到前端)
jsonPath && delete body.jsonPath;
jsonPath || (jsonPath = demoJsonPath);
jsonPath.includes("/") || (jsonPath = "json/" + jsonPath);
//判断给定的路径是否存在
fs.exists(jsonPath, exists => {
if (exists) {
CURD({req, res, jsonPath, body});
} else {
mkdirs(jsonPath, () => fs.writeFile(jsonPath, "[]", err => {
console.log(`${$g.date.nowtime()}创建${jsonPath}${err ? "失败" : "成功"}`);
CURD({req, res, jsonPath, body});
}));
}
});
});
在index.js最后一行加入
app.use(API_PATH, require(`.${API_PATH}/demo/CURD.base`));//增删改查数据(基础版、免登陆、无鉴权)
运行
node index