我开发了一个纯node.js REST应用服务器,它连接到MSSQL DB并使用端点来请求员工记录。
当我请求所有员工记录或使用REST GET请求请求一个员工记录时,我收到重复记录。响应具有记录集和记录集部分。这是否正确,如果是,我该如何防止重复记录?
非常感谢您的帮助。
db.js
exports.executeSql = function (sql, callback) {
var conn = new sqlDb.ConnectionPool(settings.dbConfig);
conn.connect()
.then(function () {
var req = new sqlDb.Request(conn);
req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
};
employee.js
var db = require("../core/db");
var httpMsgs = require("../core/httpMsgs");
var util = require("util");
exports.getList = function (req, resp) {
db.executeSql("SELECT * FROM EMPLOYEE", function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
httpMsgs.showJSON(req, resp, data);
}
});
};
exports.get = function (req, resp, empno) {
db.executeSql("SELECT * FROM EMPLOYEE WHERE EMPLOYEE_NUMBER =" + empno, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else if (data.recordset >= "0") {
(httpMsgs.showJSON(req, resp, data));
}
else {
httpMsgs.show404(req, resp, err);
}
});
};
server.js
var http = require("http");
var emp = require("../controllers/employees");
var settings = require("../settings");
var httpMsgs = require("./httpMsgs");
http.createServer(function (req, resp) {
switch (req.method) {
case "GET":
if (req.url === "/") {
httpMsgs.showHome(req, resp);
}
else if (req.url === "/employees") {
emp.getList(req, resp);
}
else {
var empnoPatt = "[A-Za-z0-9_]+";
var patt = new RegExp("/employees/" + empnoPatt);
if (patt.test(req.url)) {
patt = new RegExp(empnoPatt);
var empno = req.url.split('/')[2];
emp.get(req, resp, empno);
}
else {
httpMsgs.show404(req, resp);
}
}
break;
case "POST":
if (req.url === "/employees") {
var reqBody = "";
req.on("data", function (data){
reqBody += data;
if (reqBody.length > 1e7) //10MB
{
httpMsgs.show413(req, resp);
};
});
}
else {
httpMsgs.show404(req, resp);
}
break;
case "PUT":
if (req.url === "/employees") {
}
else {
httpMsgs.show404(req, resp);
}
break;
case "DELETE":
if (req.url === "/employees") {
}
else {
httpMsgs.show404(req, resp);
}
break;
default:
httpMsgs.show405(req, resp);
break;
}
}).listen(settings.webPort, function () {
console.log("Server Started Listening at: " + settings.webPort);
});
这是从JSON响应
返回stringify的httpMsgsexports.showJSON = function (req, resp, data) {
resp.writeHead(200, { "Content-Type": "application/json" });
resp.write(JSON.stringify(data));
resp.end();
};
这是我在请求员工记录时返回的JSON响应,其中employee_number = 100
{
"recordsets": [
[
{
"RECORD_KEY": "951112558721130050",
"EMPLOYEE_NUMBER": "100",
"FIRST_NAME": "SAMPLE CLERK",
"LAST_NAME": null,
}
]
],
"recordset": [
{
"RECORD_KEY": "951112558721130050",
"EMPLOYEE_NUMBER": "100",
"FIRST_NAME": "SAMPLE CLERK",
"LAST_NAME": null,
}
],
"output": {},
"rowsAffected": [
1
]
}