@bee.js/node 0.0.58 → 0.0.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/beehive.js +425 -422
  2. package/package.json +1 -1
package/beehive.js CHANGED
@@ -1,493 +1,496 @@
1
- const log = require('./lib/beeHive/log')
2
- const headers = require('./lib/beeHive/headers')
3
- const beeORM = require('./lib/ORM/beeORM')
4
- const beeDBA = require('./lib/DBA/beeDBA')
5
- const beeJWT = require('./lib/JWT/beeJWT')
6
- const beeTools = require('./tools/beeTools')
1
+ const log = require("./lib/beeHive/log");
2
+ const headers = require("./lib/beeHive/headers");
3
+ const beeORM = require("./lib/ORM/beeORM");
4
+ const beeDBA = require("./lib/DBA/beeDBA");
5
+ const beeJWT = require("./lib/JWT/beeJWT");
6
+ const beeTools = require("./tools/beeTools");
7
7
 
8
8
  module.exports = function hive(req = {}, res = {}, model = null) {
9
-
10
- model = model && typeof(model)==="string"
11
- ? global.configs.models[model]
12
- : model
13
-
14
- let script = [{ main: true, model: model, ids: [], select: [], where: [], binds: [], orderBy: [], limit: [], fields: [] }]
15
- let data = res.data || {}
16
- let counters = res.counters || {}
17
- let inserts = res.inserts || []
18
- let debug = res.debug || []
19
- let error = res.error || false
20
- let errorCode = res.errorCode || 0
21
- let mainContainer = null
22
- let models = global.models
23
- let relWhere = {}
24
-
25
- const dbExec = async function(SQL, binds = [], params = {}) {
26
-
27
- let result = []
28
-
29
- try {
30
- if(global.configs.debug)
31
- console.log(`
9
+ model =
10
+ model && typeof model === "string" ? global.configs.models[model] : model;
11
+
12
+ let script = [
13
+ {
14
+ main: true,
15
+ model: model,
16
+ ids: [],
17
+ select: [],
18
+ where: [],
19
+ binds: [],
20
+ orderBy: [],
21
+ limit: [],
22
+ fields: [],
23
+ },
24
+ ];
25
+ let data = res.data || {};
26
+ let counters = res.counters || {};
27
+ let inserts = res.inserts || [];
28
+ let debug = res.debug || [];
29
+ let error = res.error || false;
30
+ let errorCode = res.errorCode || 0;
31
+ let mainContainer = null;
32
+ let models = global.models;
33
+ let relWhere = {};
34
+
35
+ const dbExec = async function (SQL, binds = [], params = {}) {
36
+ let result = [];
37
+
38
+ try {
39
+ if (global.configs.debug)
40
+ console.log(`
32
41
  ${SQL}
33
- `)
34
-
35
- global.beeDBPool = global.beeDBPool || beeORM.createPool(global.configs)
36
- result = await global.beeDBPool.query(SQL, binds)
37
-
38
- } catch(e) {
39
- log("####### DB ERROR:")
40
- log(e)
41
- error = e
42
- errorCode = 502
43
- } finally {
44
- if(global.configs.debug) debug.push(SQL)
45
- if(global.configs.debug && binds) debug.push(binds)
46
-
47
- if(params.container) {
48
- data[params.container] = result[0]
49
-
50
- if(counters)
51
- counters[params.container] = (result[0] || []).length
52
- }
53
-
54
- return result[0]
55
- }
42
+ `);
43
+
44
+ global.beeDBPool = global.beeDBPool || beeORM.createPool(global.configs);
45
+ result = await global.beeDBPool.query(SQL, binds);
46
+ } catch (e) {
47
+ log("####### DB ERROR:");
48
+ log(e);
49
+ error = e;
50
+ errorCode = 502;
51
+ } finally {
52
+ if (global.configs.debug) debug.push(SQL);
53
+ if (global.configs.debug && binds) debug.push(binds);
54
+
55
+ if (params.container) {
56
+ data[params.container] = result[0];
57
+
58
+ if (counters) counters[params.container] = (result[0] || []).length;
59
+ }
60
+
61
+ return result[0];
56
62
  }
63
+ };
64
+
65
+ return Object.assign({}, res, {
66
+ data,
67
+ counters,
68
+ inserts,
69
+ debug,
70
+ error,
71
+ errorCode,
72
+ script,
73
+ models,
74
+ beeDBA,
75
+ token: beeJWT,
76
+ configs: this.config,
77
+ headers,
78
+ dbExec,
79
+
80
+ dbEngine: async function () {
81
+ error = !script[0].model
82
+ ? `MODEL NOT FOUND` // TODO refazer
83
+ : error;
84
+
85
+ if (error) return this;
86
+
87
+ let sqlSelect = beeORM.sqlSelect;
88
+ let q = beeORM.quote;
89
+ let relTables = [];
90
+ let relIds = [];
91
+ let relNow = null;
92
+ let relPrev = null;
93
+ let relJoin = {};
94
+ let parentTable = null;
95
+ let i = -1;
96
+
97
+ for (let _script of script) {
98
+ i++;
99
+
100
+ let model = _script.model;
101
+ let binds = _script.binds || [];
102
+ let modelName = model.name || model.table;
103
+ data[modelName] = null;
104
+
105
+ if (i === 0) {
106
+ mainContainer = modelName;
107
+ ids = model.ids;
108
+ } else {
109
+ ids = relTables.filter((a) => a.table == model.table)[0]; //['idsFromFieldB']
110
+ ids = ids ? ids.idsFromFieldB : [];
111
+
112
+ parentTable = script[i - 1].model.table;
113
+
114
+ // rels
115
+ for (let _relField in model.relations) {
116
+ let array = model.relations[_relField].split(".");
117
+ let _parentTable = array[0];
118
+ let _parentField = array[1].split(" ")[0];
119
+
120
+ binds = binds.length ? binds : script[0].binds;
121
+
122
+ if (_parentTable !== parentTable) continue;
123
+
124
+ relJoin[_parentTable] = !relJoin[_parentTable]
125
+ ? `INNER JOIN ${q(_parentTable)} ON ${q(
126
+ _parentTable
127
+ )}.${_parentField} = ${models[modelName].table}.${_relField} `
128
+ : relJoin[_parentTable] +
129
+ `AND ${q(_parentTable)}.${_parentField} = ${
130
+ models[modelName].table
131
+ }.${_relField} `;
132
+ }
133
+ }
57
134
 
58
- return Object.assign(
59
- {},
60
- res, {
61
- data,
62
- counters,
63
- inserts,
64
- debug,
65
- error,
66
- errorCode,
67
- script,
68
- models,
69
- beeDBA,
70
- token: beeJWT,
71
- configs: this.config,
72
- headers,
73
- dbExec,
74
-
75
- dbEngine: async function() {
76
-
77
- error = !script[0].model
78
- ? `MODEL NOT FOUND` // TODO refazer
79
- : error
80
-
81
- if(error) return this
82
-
83
- let sqlSelect = beeORM.sqlSelect
84
- let q = beeORM.quote
85
- let relTables = []
86
- let relIds = []
87
- let relNow = null
88
- let relPrev = null
89
- let relJoin = {}
90
- let parentTable = null
91
- let i = -1
92
-
93
- for(let _script of script) {
94
- i++
95
-
96
- let model = _script.model
97
- let binds = _script.binds || []
98
- let modelName = model.name || model.table
99
- data[modelName] = null
100
-
101
- if(i === 0) {
102
- mainContainer = modelName
103
- ids = model.ids
104
- } else {
105
- ids = relTables.filter((a) => a.table == model.table)[0]//['idsFromFieldB']
106
- ids = ids ? ids.idsFromFieldB : []
107
-
108
- parentTable = script[i-1].model.table
109
-
110
- // rels
111
- for(let _relField in model.relations) {
112
- let array = model.relations[_relField].split('.')
113
- let _parentTable = array[0]
114
- let _parentField = array[1].split(' ')[0]
115
-
116
- binds = binds.length
117
- ? binds
118
- : script[0].binds
119
-
120
- if(_parentTable !== parentTable) continue
121
-
122
- relJoin[_parentTable] = !relJoin[_parentTable]
123
- ? `INNER JOIN ${q(_parentTable)} ON ${q(_parentTable)}.${_parentField} = ${models[modelName].table}.${_relField} `
124
- : relJoin[_parentTable] + `AND ${q(_parentTable)}.${_parentField} = ${models[modelName].table}.${_relField} `
125
-
126
- }
127
- }
128
-
129
- let fields = script[0]['fields'].concat((req.onlyFields||{})[model.table] || [])
130
-
131
- let SQL = sqlSelect(
132
- model,
133
- ids,
134
- {
135
- select: script[0]['select'],
136
- where: script[0]['where'],
137
- orderBy: script[0]['orderBy'],
138
- limit: script[0]['limit'],
139
- joins: '',
140
- fields,
141
- middlewareParams: req.middleware,
142
- },
143
- );
144
-
145
- if(i > 0)
146
- for(let ii = i-1; ii>=0; ii--)
147
- SQL[2] += relJoin[script[ii].model.table]
148
-
149
- relWhere[model.table] = SQL[3]
150
-
151
- await dbExec(SQL.join('').trim()+';', binds, {container: modelName})
152
-
153
- continue
154
- }
155
-
156
- return
157
- },
158
-
159
- relations: function(rels, _default = '') {
160
- rels = rels || _default
161
-
162
- if(!rels) return this
163
-
164
- rels = rels.split('.')
165
-
166
- for(let model of rels)
167
- if(models[model])
168
- script.push( { model: models[model], relation: true } )
169
- else
170
- (error = `RELATION ${model} NOT FOUND`) && (errorCode = 500)
171
-
172
- return this
173
- },
174
-
175
- select: function(model, ids) {
176
-
177
- model = (typeof(model)==="string") ? models[model] : model
178
-
179
- script.push( { model: model, ids: ids } )
180
-
181
- return this
182
- },
183
-
184
- get: async function() {
185
-
186
- await this.dbEngine()
135
+ let fields = script[0]["fields"].concat(
136
+ (req.onlyFields || {})[model.table] || []
137
+ );
187
138
 
188
- return this
189
- },
139
+ let SQL = sqlSelect(model, ids, {
140
+ select: script[0]["select"],
141
+ where: script[0]["where"],
142
+ orderBy: script[0]["orderBy"],
143
+ limit: script[0]["limit"],
144
+ joins: "",
145
+ fields,
146
+ middlewareParams: req.middleware,
147
+ });
190
148
 
191
- find: async function(...values) {
192
- if(values.length)
193
- (model.indexes.keys || Object.keys(model.schema)[0])
194
- .split(",")
195
- .map((pk, i) => {
196
- console.log(pk)
197
- script[0].where.push(`${pk.trim()} = ?`)
198
- script[0].binds.push(values[i])
199
- })
200
-
201
- await this.dbEngine()
149
+ if (i > 0)
150
+ for (let ii = i - 1; ii >= 0; ii--)
151
+ SQL[2] += relJoin[script[ii].model.table];
202
152
 
203
- if(data[mainContainer]?.length)
204
- data[mainContainer] = data[mainContainer][0]
153
+ relWhere[model.table] = SQL[3];
205
154
 
206
- return this
207
- },
155
+ await dbExec(SQL.join("").trim() + ";", binds, {
156
+ container: modelName,
157
+ });
208
158
 
209
- first: async function() { //TODO auditar
210
-
211
- await this.dbEngine()
159
+ continue;
160
+ }
212
161
 
213
- if(data[mainContainer]?.length)
214
- data[mainContainer] = data[mainContainer][0]
162
+ return;
163
+ },
215
164
 
216
-
217
- return this
218
- },
165
+ relations: function (rels, _default = "") {
166
+ rels = rels || _default;
219
167
 
220
- last: async function() {
168
+ if (!rels) return this;
221
169
 
222
- await this.dbEngine()
223
-
224
- data[mainContainer] = data[mainContainer][data[mainContainer].length-1]
170
+ rels = rels.split(".");
225
171
 
226
- return this
227
- },
172
+ for (let model of rels)
173
+ if (models[model])
174
+ script.push({ model: models[model], relation: true });
175
+ else (error = `RELATION ${model} NOT FOUND`) && (errorCode = 500);
228
176
 
229
- where: function(where, binds) {
177
+ return this;
178
+ },
230
179
 
231
- script[0]['where'].push(where)
180
+ select: function (model, ids) {
181
+ model = typeof model === "string" ? models[model] : model;
232
182
 
233
- if(binds)
234
- script[0]['binds'] = script[0]['binds'].concat(binds)
183
+ script.push({ model: model, ids: ids });
235
184
 
236
- return this
237
- },
185
+ return this;
186
+ },
238
187
 
239
- whereIf: function(condition, where, binds) {
240
- if(condition)
241
- script[0]['where'].push(where)
188
+ get: async function () {
189
+ await this.dbEngine();
242
190
 
243
- if(condition && binds)
244
- script[0]['binds'].push(typeof(binds) === "function" ? binds() : binds)
245
-
246
- return this
247
- },
191
+ return this;
192
+ },
248
193
 
249
- whereIn: function(field, array = []) {
250
- array = array
251
- .map(row => {
252
- let val = row[field]
253
-
254
- switch (model.schema[field].type) {
255
- case "char":
256
- case "varchar":
257
- case "text":
258
- case "string":
259
- return `'${val}'`
260
- case "guid":
261
- case "uuid":
262
- return val ? beeTools.guidToBin(val) : null
263
- default:
264
- return val
265
- }
266
- })
267
- .join(",")
194
+ find: async function (...values) {
195
+ if (values.length)
196
+ (model.indexes.keys || Object.keys(model.schema)[0])
197
+ .split(",")
198
+ .map((pk, i) => {
199
+ console.log(pk);
200
+ script[0].where.push(`${pk.trim()} = ?`);
201
+ script[0].binds.push(values[i]);
202
+ });
268
203
 
269
- script[0]['where'].push(`${model.table}.${field} IN(${array})`)
204
+ await this.dbEngine();
270
205
 
271
- return this
272
- },
206
+ if (data[mainContainer]?.length)
207
+ data[mainContainer] = data[mainContainer][0];
273
208
 
274
- binds: function(...params) {
209
+ return this;
210
+ },
275
211
 
276
- params.map(bind=> script[0]['binds'].push(bind))
212
+ first: async function () {
213
+ //TODO auditar
277
214
 
278
- return this
279
- },
215
+ await this.dbEngine();
280
216
 
281
- orderBy: function(...fields) {
217
+ if (data[mainContainer]?.length)
218
+ data[mainContainer] = data[mainContainer][0];
282
219
 
283
- script[0]['orderBy'].push(fields.join(', '))
220
+ return this;
221
+ },
284
222
 
285
- return this
286
- },
223
+ last: async function () {
224
+ await this.dbEngine();
287
225
 
288
- orderByIf: function(condition, ...fields) {
289
- if (condition)
290
- script[0]['orderBy'].push(fields.join(', '))
226
+ data[mainContainer] = data[mainContainer][data[mainContainer].length - 1];
291
227
 
292
- return this
293
- },
228
+ return this;
229
+ },
294
230
 
295
- limit: function(...params) {
231
+ where: function (where, binds) {
232
+ script[0]["where"].push(where);
296
233
 
297
- script[0]['limit'].push(params.join(","))
234
+ if (binds) script[0]["binds"] = script[0]["binds"].concat(binds);
298
235
 
299
- return this
300
- },
236
+ return this;
237
+ },
301
238
 
302
- fields: function(...fields) {
239
+ whereIf: function (condition, where, binds) {
240
+ if (condition) script[0]["where"].push(where);
303
241
 
304
- script[0]['fields'] = fields
242
+ if (condition && binds)
243
+ script[0]["binds"].push(typeof binds === "function" ? binds() : binds);
305
244
 
306
- return this
307
- },
245
+ return this;
246
+ },
308
247
 
309
- fieldsIf: function(condition, fields) {
248
+ whereIn: function (field, array = []) {
249
+ array = [
250
+ ...new Set(
251
+ array.map((row) => {
252
+ let val = row[field];
310
253
 
311
- if(condition)
312
- script[0]['fields'] = fields
254
+ // TODO colocar escape para sql injection
255
+ switch (model.schema[field].type) {
256
+ case "char":
257
+ case "varchar":
258
+ case "text":
259
+ case "string":
260
+ return `'${val}'`;
261
+ case "guid":
262
+ case "uuid":
263
+ return val ? beeTools.guidToBin(val) : null;
264
+ default:
265
+ return val;
266
+ }
267
+ })
268
+ ),
269
+ ].join(",");
270
+
271
+ script[0]["where"].push(`${model.table}.${field} IN(${array})`);
272
+
273
+ return this;
274
+ },
275
+
276
+ binds: function (...params) {
277
+ params.map((bind) => script[0]["binds"].push(bind));
278
+
279
+ return this;
280
+ },
281
+
282
+ orderBy: function (...fields) {
283
+ script[0]["orderBy"].push(fields.join(", "));
284
+
285
+ return this;
286
+ },
287
+
288
+ orderByIf: function (condition, ...fields) {
289
+ if (condition) script[0]["orderBy"].push(fields.join(", "));
290
+
291
+ return this;
292
+ },
293
+
294
+ limit: function (...params) {
295
+ script[0]["limit"].push(params.join(","));
296
+
297
+ return this;
298
+ },
299
+
300
+ fields: function (...fields) {
301
+ script[0]["fields"] = fields;
302
+
303
+ return this;
304
+ },
313
305
 
314
- return this
315
- },
306
+ fieldsIf: function (condition, fields) {
307
+ if (condition) script[0]["fields"] = fields;
308
+
309
+ return this;
310
+ },
311
+
312
+ search: function (string = "", fields = [], relevance = [1, 2, 3, 4, 5]) {
313
+ if (!string) return this;
314
+
315
+ let where = [];
316
+ let orderBy = [];
317
+ let words = string.split(" ");
318
+ fields = beeORM.parseArray(fields);
319
+ fields = fields.length ? fields : Object.keys(model.schema);
316
320
 
317
- search: function(string = "", fields = [], relevance = [1, 2, 3, 4, 5]) {
318
- if(!string) return this
321
+ fields.map((field) => {
322
+ orderBy.push(
323
+ `WHEN ${field} = '${string}' THEN ${
324
+ relevance[0]
325
+ } WHEN ${field} LIKE '${string}%' THEN ${
326
+ relevance[1]
327
+ } WHEN ${field} LIKE '%${string}%' THEN ${
328
+ relevance[2]
329
+ } WHEN ${field} LIKE '%${string.replace(/ /g, "%")}%' THEN ${
330
+ relevance[3]
331
+ }`
332
+ );
319
333
 
320
- let where = []
321
- let orderBy = []
322
- let words = string.split(" ")
323
- fields = beeORM.parseArray(fields)
324
- fields = fields.length ? fields : Object.keys(model.schema)
334
+ words.map((word, i) => {
335
+ where.push(`${field} LIKE '%${word}%'`);
325
336
 
337
+ if (words.length > 1)
338
+ orderBy.push(
339
+ `WHEN ${field} = '${word}' THEN ${
340
+ relevance[4] * (i + 1)
341
+ } WHEN ${field} LIKE '${word}%' THEN ${
342
+ relevance[4] * (i + 1) + relevance[1]
343
+ } WHEN ${field} LIKE '%${word}%' THEN ${
344
+ relevance[4] * (i + 1) + relevance[2]
345
+ }`
346
+ );
347
+ });
348
+ });
326
349
 
327
- fields
328
- .map((field)=> {
350
+ script[0]["where"].push(`(${where.join(" OR ")})`);
351
+ script[0]["orderBy"].unshift(
352
+ `CASE ${orderBy.join(" ")} ELSE ${100000} END ASC`
353
+ );
329
354
 
330
- orderBy.push(`WHEN ${field} = '${string}' THEN ${relevance[0]} WHEN ${field} LIKE '${string}%' THEN ${relevance[1]} WHEN ${field} LIKE '%${string}%' THEN ${relevance[2]} WHEN ${field} LIKE '%${string.replace(/ /g, "%")}%' THEN ${relevance[3]}`)
331
-
332
- words
333
- .map((word, i)=> {
334
-
335
- where.push(`${field} LIKE '%${word}%'`)
355
+ return this;
356
+ },
336
357
 
337
- if(words.length > 1)
338
- orderBy.push(`WHEN ${field} = '${word}' THEN ${(relevance[4] * (i+1))} WHEN ${field} LIKE '${word}%' THEN ${(relevance[4] * (i+1)) + relevance[1]} WHEN ${field} LIKE '%${word}%' THEN ${(relevance[4] * (i+1)) + relevance[2]}`)
339
- })
340
- })
358
+ insert: async function (_data, params = {}) {
359
+ //data = beeORM.forceData(data, req)
341
360
 
342
- script[0]['where'].push(`(${where.join(' OR ')})`)
343
- script[0]['orderBy'].unshift(`CASE ${orderBy.join(' ')} ELSE ${100000} END ASC`)
361
+ if (model.relations && params.relations)
362
+ await Promise.all(
363
+ Object.keys(model.relations).map(async (field) => {
364
+ let where = [];
365
+ let array = model.relations[field].split(" ")[0].split(".");
366
+ let parentTable = array[0];
367
+ let parentField = array[1];
368
+ let parentRels = global.configs.models[parentTable].relations;
344
369
 
345
- return this
346
- },
370
+ Object.keys(parentRels).map((fieldRel) =>
371
+ where.push(
372
+ `${fieldRel} = '${params.relations[parentTable][fieldRel]}'`
373
+ )
374
+ );
347
375
 
348
- insert: async function(_data, params = {}) {
376
+ let SQL = `SELECT ${parentField} FROM ${parentTable} WHERE ${where.join(
377
+ " AND "
378
+ )}`;
349
379
 
350
- //data = beeORM.forceData(data, req)
380
+ SQL = await dbExec(SQL);
351
381
 
352
- if(model.relations && params.relations)
353
- await Promise
354
- .all(
355
- Object
356
- .keys(model.relations)
357
- .map(async field => {
358
- let where = []
359
- let array = model.relations[field].split(" ")[0].split(".")
360
- let parentTable = array[0]
361
- let parentField = array[1]
362
- let parentRels = global.configs.models[parentTable].relations
382
+ Array.isArray(_data)
383
+ ? _data.map((a) => (a[parentField] = SQL[0][parentField]))
384
+ : (_data[parentField] = SQL[0][parentField]);
385
+ })
386
+ );
363
387
 
364
- Object
365
- .keys(parentRels)
366
- .map(fieldRel => where.push(`${fieldRel} = '${params.relations[parentTable][fieldRel]}'`))
367
-
368
- let SQL = `SELECT ${parentField} FROM ${parentTable} WHERE ${where.join(" AND ")}`
369
-
370
- SQL = await dbExec(SQL)
388
+ let onlyFields = script[0].fields.concat(
389
+ (req.onlyFields || {})[model.table] || []
390
+ );
391
+ let sql = beeORM.sqlInsertUpdate(model, _data, onlyFields, "INSERT");
392
+
393
+ _data = await dbExec(sql.SQL, sql.binds);
394
+
395
+ inserts.push({ ..._data, model: model.table });
396
+ this.insertId = _data.insertId;
397
+
398
+ return { ...this, result: { ...sql.result, ..._data } };
399
+ },
400
+
401
+ update: async function (data, ids = []) {
402
+ // TODO criar auditoria
403
+
404
+ //data = beeORM.forceData(data, req)
405
+
406
+ let onlyFields = script[0].fields.concat(
407
+ (req.onlyFields || {})[model.table] || []
408
+ );
409
+ let sql = beeORM.sqlInsertUpdate(model, data, onlyFields, "UPDATE");
410
+
411
+ sql.SQL += beeORM.modelSqlWhere(model, ids, req.middleware);
412
+ sql.SQL += script[0]["where"].length
413
+ ? (!ids.length ? " WHERE " : " AND ") + script[0]["where"].join(" AND ")
414
+ : "";
415
+
416
+ data = await dbExec(sql.SQL, script[0]["binds"]);
417
+
418
+ return { ...this, result: { ...sql.result, ...data } };
419
+ },
420
+
421
+ delete: async function (ids) {
422
+ const q = beeORM.quote;
423
+
424
+ ids = ids && typeof ids !== "object" ? ids.toString().split(",") : ids;
425
+
426
+ SQL = "DELETE FROM " + q(model.table);
427
+ SQL += beeORM.modelSqlWhere(model, ids, req.middleware);
428
+ SQL += script[0]["where"].length
429
+ ? (!ids.length ? " WHERE " : " AND ") + script[0]["where"].join(" AND ")
430
+ : "";
371
431
 
372
- Array.isArray(_data)
373
- ? _data.map(a => a[parentField] = SQL[0][parentField])
374
- : _data[parentField] = SQL[0][parentField]
375
- })
376
- )
377
-
378
- let onlyFields = script[0].fields.concat((req.onlyFields||{})[model.table] || [])
379
- let sql = beeORM.sqlInsertUpdate(model, _data, onlyFields, 'INSERT')
432
+ data = await dbExec(SQL);
380
433
 
381
- _data = await dbExec(sql.SQL, sql.binds)
434
+ return this;
435
+ },
382
436
 
383
- inserts.push({..._data, model: model.table})
384
- this.insertId = _data.insertId
437
+ table: async function (table, where) {
438
+ const q = beeORM.quote;
385
439
 
386
- return {...this, result: {...sql.result,..._data}}
387
- },
440
+ SQL = "SELECT * FROM " + q(table);
441
+ SQL += where ? ` WHERE ${where};` : "";
388
442
 
389
- update: async function(data, ids = []) { // TODO criar auditoria
390
-
391
- //data = beeORM.forceData(data, req)
392
-
393
- let onlyFields = script[0].fields.concat((req.onlyFields||{})[model.table] || [])
394
- let sql = beeORM.sqlInsertUpdate(model, data, onlyFields, 'UPDATE')
395
-
396
- sql.SQL += beeORM.modelSqlWhere(model, ids, req.middleware)
397
- sql.SQL += script[0]['where'].length
398
- ? (!ids.length ? ' WHERE ' : ' AND ') + script[0]['where'].join(" AND ")
399
- : ''
400
-
401
- data = await dbExec(sql.SQL, script[0]['binds'])
443
+ let result = await dbExec(SQL);
402
444
 
403
- return {...this, result: {...sql.result, ...data}}
404
- },
445
+ data[table] = result;
446
+ counters[table] = result.length;
447
+ mainContainer = table;
405
448
 
406
- delete: async function(ids) {
449
+ return this;
450
+ },
407
451
 
408
- const q = beeORM.quote
452
+ query: async function (SQL, binds = [], container = "query") {
453
+ let result = await dbExec(SQL, binds, { container: container });
409
454
 
410
- ids = ids && typeof(ids) !== 'object'
411
- ? ids.toString().split(',')
412
- : ids
455
+ counters[container] = result ? result.length : 0;
413
456
 
414
- SQL = 'DELETE FROM ' + q(model.table)
415
- SQL += beeORM.modelSqlWhere(model, ids, req.middleware)
416
- SQL += script[0]['where'].length
417
- ? (!ids.length ? ' WHERE ' : ' AND ') + script[0]['where'].join(" AND ")
418
- : ''
419
-
420
- data = await dbExec(SQL)
421
-
422
- return this
423
- },
457
+ return this;
458
+ },
424
459
 
425
- table: async function(table, where) {
426
-
427
- const q = beeORM.quote
428
-
429
- SQL = 'SELECT * FROM ' + q(table)
430
- SQL += where ? ` WHERE ${where};` : ''
431
-
432
- let result = await dbExec(SQL)
433
-
434
- data[table] = result
435
- counters[table] = result.length
436
- mainContainer = table;
437
-
438
- return this
439
- },
460
+ response: function (sendData = data, action = null, status) {
461
+ let out = { data: sendData, counters, action, error };
440
462
 
441
- query: async function(SQL, binds = [], container = 'query') {
442
-
443
- let result = await dbExec(SQL, binds, {container: container})
463
+ if (inserts.length) out.inserts = inserts;
444
464
 
445
- counters[container] = (result) ? result.length : 0
446
-
447
- return this
448
- },
449
-
450
- response: function(sendData = data, action = null, status) {
451
-
452
- let out = {data: sendData, counters, action, error}
453
-
454
- if(inserts.length)
455
- out.inserts = inserts
456
-
457
- if(global.configs.debug)
458
- out.debug = debug
459
-
460
- if(status)
461
- res.status(status).send(out)
462
- else
463
- switch(req.method) {
464
- case 'DELETE' :
465
- res.status(action ? errorCode || 200 : 204).json(out)
466
- break
467
- case 'POST':
468
- res.status(errorCode || 201).json(out)
469
- break
470
- case 'PUT':
471
- res.status(errorCode || 200).json(out) // TODO deletar props irrelevantes no output
472
- break
473
- default:
474
- res.status(errorCode || 200).json(out)
475
- }
476
- },
465
+ if (global.configs.debug) out.debug = debug;
477
466
 
478
- responseError: function(error, errorCode) {
467
+ if (status) res.status(status).send(out);
468
+ else
469
+ switch (req.method) {
470
+ case "DELETE":
471
+ res.status(action ? errorCode || 200 : 204).json(out);
472
+ break;
473
+ case "POST":
474
+ res.status(errorCode || 201).json(out);
475
+ break;
476
+ case "PUT":
477
+ res.status(errorCode || 200).json(out); // TODO deletar props irrelevantes no output
478
+ break;
479
+ default:
480
+ res.status(errorCode || 200).json(out);
481
+ }
482
+ },
479
483
 
480
- let out = {error: {message: error || 'an error has occurred'}}
484
+ responseError: function (error, errorCode) {
485
+ let out = { error: { message: error || "an error has occurred" } };
481
486
 
482
- if(global.configs.debug)
483
- out.debug = debug
487
+ if (global.configs.debug) out.debug = debug;
484
488
 
485
- res.status(errorCode || 500).send(out)
486
- },
489
+ res.status(errorCode || 500).send(out);
490
+ },
487
491
 
488
- ifNull(param) {
489
- return !this.data ? param : this
490
- },
491
- }
492
- )
493
- }
492
+ ifNull(param) {
493
+ return !this.data ? param : this;
494
+ },
495
+ });
496
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bee.js/node",
3
- "version": "0.0.58",
3
+ "version": "0.0.59",
4
4
  "description": "A JavaScript framework for making Node.js API´s",
5
5
  "main": "index.js",
6
6
  "scripts": {