1 | var developerConsole = require('letsnet-developerconsole')()
|
2 | console.developer = developerConsole.developerConsole
|
3 |
|
4 | var mongoose = require('mongoose')
|
5 | const fs = require('fs')
|
6 | var Queue = require('./queue')
|
7 |
|
8 | var API = function(defaults) {
|
9 | mongodb = null
|
10 | mongooseCredentials = null
|
11 | queue = null
|
12 | this.middlewares = {}
|
13 | this.schemas = {}
|
14 | this.wrongRequest = null
|
15 | }
|
16 |
|
17 | API.prototype.addMiddleware = function(name, func) {
|
18 | this.middlewares[name] = func
|
19 | }
|
20 |
|
21 | API.prototype.mongoConnect = function() {
|
22 | let opts = {}
|
23 | if(this.mongooseCredentials == null) throw 'Please set mongooseCredentials with setMongooseCredentials(object) function ...'
|
24 | else this.mongodb = mongoose.createConnection('mongodb://' + this.mongooseCredentials.user + ':' + this.mongooseCredentials.passwd + this.mongooseCredentials.url, opts)
|
25 | }
|
26 |
|
27 | API.prototype.mongoClose = function() {
|
28 | this.mongodb.close()
|
29 | mongoose.disconnect()
|
30 | this.openSchema = null
|
31 | }
|
32 |
|
33 | API.prototype.setMongooseCredentials = function(object) {
|
34 | if(object.user === 'undefined' || object.user == null) throw 'You must define the \'USER\' of the connection!'
|
35 | else if(object.url === 'undefined' || object.url == null) throw 'You must define the \'URL\' of the connection!'
|
36 | else if(object.passwd === 'undefined' || object.passwd == null) throw 'You must define the \'PASSWORD\' of the connection!'
|
37 | else { this.mongooseCredentials = object }
|
38 | }
|
39 |
|
40 | API.prototype.addSchema = function(database, object) {
|
41 | if(this.mongodb == null) throw 'Please set a connection with mongoConnect function!'
|
42 | else if(this.schemas.hasOwnProperty(database)) throw 'Duplicated schema... u idiot'
|
43 | else this.schemas[database] = this.mongodb.model(database, new mongoose.Schema(object))
|
44 | }
|
45 |
|
46 | API.prototype.addFunction = function(defs, rFunction) {
|
47 | if(rFunction instanceof Function) {
|
48 | this[defs.name] = function() {
|
49 | this.queue = new Queue(arguments)
|
50 | this.queue.setMasterFunction(defs.schema, rFunction)
|
51 | this.queue.next()
|
52 | }
|
53 | }
|
54 | else new Error('The second parameter must be a function!')
|
55 | }
|
56 |
|
57 | API.prototype.checkResponses = function(requests) {
|
58 | for (const request of requests) {
|
59 | if(request.type != 'success') {
|
60 | this.wrongRequest = request
|
61 | return false
|
62 | }
|
63 | }
|
64 | return true
|
65 | }
|
66 |
|
67 | module.exports = API |
\ | No newline at end of file |