mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:56:27 +00:00
53 lines
2.0 KiB
JavaScript
53 lines
2.0 KiB
JavaScript
const model = require("./pooling.model");
|
|
const { logger } = require("../../helpers/winston.logger");
|
|
|
|
function respond(res, code, message, data = []) {
|
|
return res.status(200).json({ code, message, data });
|
|
}
|
|
|
|
function failure(res, error) {
|
|
logger.error("Pooling failed | " + (error.code || error.name));
|
|
if (error.code === "POOLING_CARD_CONFLICT") return respond(res, "409", "Fail insert data card product");
|
|
return respond(res, "500", process.env.NODE_ENV === "production"
|
|
? "500 internal server error - backend server." : error.message);
|
|
}
|
|
|
|
async function runBatches(res, operation, name, empty, complete) {
|
|
let count = 0;
|
|
try {
|
|
for (;;) {
|
|
const batch = await operation();
|
|
if (batch.busy) return respond(res, "409", "Pooling is being processed. Please retry.");
|
|
if (!batch.count) return respond(res, ...(count ? complete : empty));
|
|
count += batch.count;
|
|
logger.info("Pooling " + name + " batch committed | count=" + batch.count);
|
|
}
|
|
} catch (error) {
|
|
return failure(res, error);
|
|
}
|
|
}
|
|
|
|
const validateData = (req, res) => runBatches(res, model.validateBatch, "validate",
|
|
["00", "No Pooling Data"], ["00", "Validate success"]);
|
|
|
|
const insertCardProduct = (req, res) => runBatches(res, model.syncBatch, "sync",
|
|
["409", "No data valid"], ["00", "Success"]);
|
|
|
|
async function insertPooling(req, res) {
|
|
const { batch, data, card_number, uid } = req.body || {};
|
|
const cards = batch ? data : [{ card_number, uid }];
|
|
if (!Array.isArray(cards) || cards.length === 0) return respond(res, "409", "Data is required");
|
|
if (cards.some((card) => !card?.card_number)) return respond(res, "409", "Card Number is required");
|
|
if (cards.some((card) => !card?.uid)) return respond(res, "409", "uid is required");
|
|
|
|
try {
|
|
await model.insertRawCards(cards);
|
|
logger.info("Pooling raw batch committed | count=" + cards.length);
|
|
return respond(res, "00", "Success insert data");
|
|
} catch (error) {
|
|
return failure(res, error);
|
|
}
|
|
}
|
|
|
|
module.exports = { validateData, insertCardProduct, insertPooling };
|