Last active
May 26, 2020 07:45
-
-
Save alfari16/8c5792f7605d3f531fc3827503f4831f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| const router = require('express').Router() | |
| const kue = require('kue') | |
| const queue = kue.createQueue() | |
| queue.process('order', async (job, done) => { | |
| try { | |
| let outOfStock = { | |
| bool: false, | |
| data: [], | |
| } | |
| let allProduct = (await Product.findAll({ | |
| where: { | |
| id: { | |
| in: job.data.items.map((el) => el.id), | |
| }, | |
| }, | |
| attributes: ['id', 'stock'], | |
| })).map((el) => { | |
| if (el.stock < job.data.items.find((inner) => inner.id === el.id).item) { | |
| outOfStock.bool = true | |
| outOfStock.data.push(el) | |
| } | |
| return { | |
| id: el.id, | |
| stock: el.stock, | |
| } | |
| }) | |
| if (outOfStock.bool) { | |
| return done( | |
| JSON.stringify({ | |
| errorMsg: 'Stuff out of Stock', | |
| data: outOfStock.data, | |
| }) | |
| ) | |
| } | |
| await Promise.all( | |
| allProduct.map((el) => { | |
| return Product.update( | |
| { | |
| stock: | |
| el.stock - | |
| job.data.items.find((inner) => inner.id === el.id).item, | |
| }, | |
| { | |
| where: { | |
| id: el.id, | |
| }, | |
| transaction, | |
| } | |
| ) | |
| }) | |
| ) | |
| done(null, 'ok') //parameter pertama berisi null untuk menandakan tidak ada error. Parameter kedua berisi nilai kembalian | |
| } catch (err) { | |
| done(err) //mengembalikan nilai error | |
| } | |
| }) | |
| router.post('order', (req, res) => { | |
| const job = queue.create('order', { | |
| items: req.body.items, | |
| /** | |
| * items berisi: | |
| * { | |
| * id, //id produk | |
| * count //jumlah produk yang diinginkan | |
| * } | |
| */ | |
| }) | |
| job.on('failed', (err) => { | |
| console.log(err) //nilai kembalian error akan dipassing disini. | |
| }) | |
| job.on('complete', (result) => { | |
| console.log(result) //nilai kembalian jika sukses akan dipassing disini. | |
| }) | |
| job.save() | |
| return res.json('Wait the queue please :)') | |
| }) | |
| module.exports = router |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment