UNPKG

2.55 kBJavaScriptView Raw
1var Ajv = require('ajv')
2var ajv = new Ajv({allErrors: true})
3
4var Queue = function(object) {
5 this.counter = 1
6 this.masterFunction = null
7 if(object[0] instanceof Function) {
8 this.queue = Object.entries(object)
9 this.sharedObject = {}
10 } else {
11 this.queue = Object.entries(object)
12 this.sharedObject = this.queue.shift()[1] || {}
13 }
14 this.queueLength = this.queue.length
15}
16
17Queue.prototype.next = function() {
18 if(this.queueLength == this.counter) {
19 var callback = this.queue.shift()[1]
20 this.masterFunction(this.sharedObject)
21 .then(function(response) {
22 /*IFLOG*/if(process.env.QUEUE_THEN_RESPONSE == 'true') console.developer.log(response)
23 callback(false, {func: response.func || 'anonymus', lCode: response.lCode || '-S', msg: response.msg || 'Sikeres lefutás!', type: response.type || 'success', document: response.document || null})
24 })
25 .catch(function(response) {
26 /*IFLOG*/if(process.env.QUEUE_CATCH_RESPONSE == 'true') console.developer.log(response)
27 callback(true, {func: response.func || 'anonymus', lCode: response.lCode || '-E', msg: response.msg || 'Sikertelen lefutás!', type: response.type || 'error'})
28 })
29 }
30 else {
31 ++this.counter
32 return this.queue.shift()[1](this.sharedObject, this)
33 }
34}
35
36Queue.prototype.stop = function(object) {
37 var callback = this.queue.pop()[1]
38 this.queue = null
39 /*IFLOG*/if(process.env.QUEUE_STOP_LOG == 'true') console.developer.log(object)
40 callback(true, {func: object.func || 'anonymus', lCode: object.lCode || '-E2', msg: object.msg || 'Sikertelen lefutás!', type: object.type || 'queue-error'})
41}
42
43Queue.prototype.setMasterFunction = function(schema, masterFunction) {
44 if(schema === undefined || schema == null) this.masterFunction = masterFunction
45 else this.masterFunction = function(object) {
46 return new Promise(function(resolve, reject) {
47 var valid = ajv.validate(schema, object)
48 /*IFLOG*/if(process.env.AJV_ERROR_LOG == 'true') console.developer.log(ajv.errors)
49 if(valid) {
50 masterFunction(object).then(function(response) {
51 resolve(response)
52 }).catch(function(response) {
53 reject(response)
54 })
55 }
56 else reject({func: '@dataChecker', lCode: '-DC', msg: 'Hibás adatokat adott meg!', type: 'data-error'})
57 })
58 }
59}
60
61module.exports = Queue
\No newline at end of file