我有两个“问题”:
我们不希望服务器返回具有真实字段名称的对象。我可以使用receive
事件来重命名它们:
const initOptions = {
receive(data, result, e) {
// data = { myid: 1, tname: 'name' }
refactorProperties(data);
// data = { myId: 1, name: 'name' }
}
};
const columnToJS = {
"myid": "myId",
"tname": "name",
"anotherdatabasefieldname": "theJSObjectProperty",
};
function refactorProperties(data) {
data.forEach(tmp => {
for(const prop in tmp) {
const newProp = columnToJS[prop];
if(newProp) {
tmp[newProp] = tmp[prop];
delete tmp[prop];
}
}
});
}
这是一个很小的对象,但实际上它会更大(连接查询等)。doc指定
这里任何数据预处理都需要快速进行,以避免性能损失。
限制是多少? pg-promise是否有帮助者或类似的东西可以通过Columns完成?
const cs = new pgp.helpers.ColumnSet([
{ name: 'myid', prop: 'myId', cnd: true /* other options */ }
{ name: 'tname', prop: 'name' /* other options */ },
{ name: 'anotherdatabasefieldname', prop: 'theJSObjectProperty' /* other options */ },
], {
table: 'mytable'
});
const query = pgp.helpers.insert(obj, cs);
// query = "INSERT INTO "mytable"("tname","anotherdatabasefieldname") VALUES('nameValue','anotherValue')"
const query2 = pgp.helpers.insert(obj, cs, true); // third params = return values ?
// query2 = "INSERT INTO "mytable"("tname","anotherdatabasefieldname") VALUES('nameValue','anotherValue') RETURNING myid AS "myId", tname AS "name", anotherdatabasefieldname AS "theJSObjectProperty"
const query3 = pgp.helpers.select(obj, cs);
// query3 = "SELECT myid AS "myId", tname AS "name", anotherdatabasefieldname AS "theJSObjectProperty" FROM mytable where [...]"
答案 0 :(得分:0)
命名空间pg-promise仅用于帮助您以与单行插入相同的方式生成多行插入和更新。就是这样,仅此而已。它并非旨在生成任何SELECT
语句,您必须自己做:
它统一了生成多行
INSERT
/UPDATE
查询和单行查询的方法。
当涉及到对许多列进行别名以及一般而言复杂的SQL查询时,应该将所有内容保留在外部SQL文件中,就像pg-promise-demo向您显示的那样。通过这种结构,您可以轻松编写各种规模和复杂度的SQL以及内联SQL文档,并让pg-promise使用它们并缩小它们以实现快速执行。
关于驼峰栏,事件receive的API随处带有示例。
有什么限制?
此限制是常识,而不是物理意义。您正在处理事件receive中来自服务器的所有数据,并且您不希望它们花费很多时间。