Last active
April 7, 2016 20:11
-
-
Save thebergamo/e0b3df83ca0b5179712d12be4b889aee to your computer and use it in GitHub Desktop.
Update valor total
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//item-order --> esse json que é enviado no POST | |
{ | |
"order": 1, | |
"product": 1, | |
"price": 10, | |
"quantity": 20 | |
} | |
// [POST] /item-order | |
function create (request, reply) { | |
let payload = request.payload; | |
payload.user = request.auth.credentials.id; | |
this.model.create(payload) | |
.then((itemOrder) => { | |
return this.database.Order.scope({ // - localiza o pedido para retornar o total(price) | |
method: ['user', request.auth.credentials.id] | |
}) | |
.findOne({ | |
attributes: ['id', 'price'], | |
where: {id: payload.order} | |
}); | |
}) | |
.then((order) => { | |
if (!order) { | |
return reply.notFound(); | |
} | |
return this.database.Product.scope({ // - localiza o produto para pegar o valor unitário(unit) | |
method: ['user', request.auth.credentials.id] | |
}).findOne({ | |
attributes: ['unit'], | |
where: {id: payload.product} | |
}); | |
}) | |
.then((product) => { | |
if (!product) { | |
return reply.notFound(); | |
} | |
let price = order.price + (product.unit * itemOrder.quantity); // - faz o calculo | |
return order.update({ price: price }, { where: { id: itemOrder.order }}); // - manda o update no pedido para atualziar o valor total | |
}) | |
.then((order) => { | |
reply(itemOrder).code(201); | |
}).catch((err) => reply.badImplementation(err.message)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment