CoolFace
Apppublic

PixelPiggy/CS_float

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
job.js86 linesDownload Raw Back to lib
1const errors = require('./../errors');2 3// A Job encapsulates fetching multiple links for a single request4class Job {5    get ip() {6        return this.req.ip;7    }8 9    constructor(req, res, isBulk) {10        this.req = req;11        this.res = res;12        this.isBulk = isBulk;13        this.remainingLinks = [];14 15        this.index = 0;16 17        this.responses = {};18    }19 20    add(link, price) {21        this.remainingLinks.push({22            link,23            price,24            job: this,25        });26    }27 28    getRemainingLinks() {29        return this.remainingLinks;30    }31 32    remainingSize() {33        return this.remainingLinks.length;34    }35 36    getLink(aParam) {37        return this.remainingLinks.find(e => e.link.getParams().a == aParam);38    }39 40    setResponseRemaining(response) {41        // Prevent operating on mutating list size42        for (const link of [...this.remainingLinks]) {43            this.setResponse(link.link.getParams().a, response);44        }45    }46 47    setResponse(assetId, response) {48        const index = this.remainingLinks.findIndex(e => e.link.getParams().a == assetId);49        if (index === -1) {50            return;51        }52 53        if (response instanceof errors.Error) {54            response = response.getJSON();55        }56 57        this.responses[assetId.toString()] = response;58        this.remainingLinks.splice(index, 1);59 60        if (this.remainingLinks.length === 0) {61            this._reply();62        }63    }64 65    _reply() {66        const keys = Object.keys(this.responses);67 68        if (keys.length === 0) {69            return;70        }71 72        if (this.isBulk || keys.length > 1) {73            this.res.json(this.responses);74        } else {75            const response = this.responses[keys[0]];76            if (response.error) {77                this.res.status(response.status).json(response);78            } else {79                this.res.json({iteminfo: response});80            }81        }82    }83}84 85module.exports = Job;86