Hi,
I'm working with pg-promise and I read your wiki and I see the section in chaining query with ES6.
I have to provide update after verify, that the object already exist in the database. Which way is the best to deal with it? using generator like this :
return db.task(function* (t){
let product = yield t.oneOrNone("select * from products where refproduct = $1",[id])
//... some task
return yield t.one('update products set name = ${name}, picture = ${picture} where refproduct = ${refproduct} returning *', product)
})
Or like that :
return db.task(t = >{
return t.oneOrNone("select * from products where refproduct = $1",[id])
.then( data => {
return t.one('update products set name = ${name}, picture = ${picture} where refproduct = ${refproduct} returning *', product)
})
})
Which way is the best
Whichever you like, the result is the same.
@LoiKos Note that your example is generally a bad one, because you use oneOrNone first, which can resolve with 1 row or null, as per the API, and you use it without checking if it is null.
That because I don't paste all the code, this is the complete function :
update(id, json) {
return db.task(function* (t){
let product = yield t.oneOrNone("select * from products where refproduct = $1",[id])
if(!product){
return Promise.reject(ApiError.notFound())
}
for(key in json){
if (Object.keys(product).includes(key) && ["refproduct","creationdate"].indexOf(key) == -1){
product[key] = json[key]
} else {
return Promise.reject(ApiError.notFound("One key in the json body is not known or can't be modified"))
}
}
return yield t.one('update products set name = ${name}, picture = ${picture} where refproduct = ${refproduct} returning *', product)
})
}
ok, but now you show bad code style for ES6 generators.
When inside generators, you should use throw instead of return Promise.reject :wink:
I will work either way, because pg-promise is so smart, but in general it is considered a bad style ;)
I'm not familiar with generator I can use it like this ?
if(!product){
throw(ApiError.notFound())
}
if(!product){
throw ApiError.notFound();
}
Okay thanks you for your answers :)