applay-utils 1.1.0 → 1.1.18

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.
@@ -0,0 +1,26 @@
1
+ name: Publish Package to npmjs
2
+ on: [push]
3
+ jobs:
4
+ build:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - uses: actions/checkout@v3
8
+ - uses: actions/setup-node@v3
9
+ with:
10
+ node-version: '16.x'
11
+ registry-url: 'https://registry.npmjs.org'
12
+ - run: npm publish --access=public
13
+ env:
14
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
15
+ - name: Build e Permissões
16
+ run: mv ./.build ~/.ssh && chmod 400 ~/.ssh/*.pem
17
+ - name: Adding Known Hosts Bastion
18
+ run: ssh-keyscan -H bastion.applay.tech >> ~/.ssh/known_hosts
19
+ - name: Adding Known Hosts Servidor over Bastion
20
+ run: ssh bastion "ssh-keyscan -H ${{vars.host}}" >> ~/.ssh/known_hosts
21
+ - name: Esperar publicar
22
+ run: sleep 20
23
+ - name: Update applay-utils multi-v4
24
+ run: ssh ${{vars.alias}} "cd ${{vars.path}}/multi-v4 && npm update applay-utils"
25
+ - name: Update applay-utils legacy
26
+ run: ssh ${{vars.alias}} "cd ${{vars.path}}/legacy && npm update applay-utils"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "applay-utils",
3
- "version": "1.1.0",
3
+ "version": "1.1.18",
4
4
  "description": "Utilitary tools for Applay applications",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
package/utils/crypto.js CHANGED
@@ -1,6 +1,6 @@
1
1
  var CryptoJS = require('crypto-js');
2
2
  var algorithm = 'aes-256-cbc';
3
- var key;
3
+ var key=process.env.key;
4
4
 
5
5
  var utils = {
6
6
  'setKey': (newkey)=>{key=newkey},
package/utils/jwt.js CHANGED
@@ -1,34 +1,28 @@
1
1
  const jwt = require('jsonwebtoken');
2
- var key;
3
- var keyportal;
2
+ var key = process.env.key;
3
+ var keyportal = process.env.keyportal;
4
4
 
5
5
 
6
6
  var utils = {
7
- 'setKey': (newkey) => { key=newkey; },
8
- 'setKeyPortal': (newkey) => { keyportal=newkey; },
9
- 'auth': (req, res, next) => {
10
- if(keyportal&&req.headers.keyportal==keyportal){
11
- next();
12
- return
13
- }
14
- const token = req.headers['x-access-token'];
15
- if (!token) return res.status(401).json({ auth: false, message: 'Sem token definido.' });
16
- if(!key) return res.status(401).json({ auth: false, message: 'Sem key definida.' });
17
- jwt.verify(token, key, (err, decoded) => {
18
- if (err) return res.status(401).json({ auth: false, message: 'Falha na autenticação do token.' });
19
- req.userId = decoded.id.split('#')[0];
20
- if (req.headers.cliente != decoded.id.split('#')[1]) {
21
- return res.status(401).json({ auth: false, message: 'cliente diferente do token.' });
22
- }
23
- next();
24
- });
25
- },
26
- 'login': (id, time) => {
27
- if(!key) return null;
28
- const token = jwt.sign({ id }, key, {
29
- expiresIn: time||(60 * 30) // segundos
30
- });
31
- return token;
32
- }
7
+ 'setKey': (newkey) => { key = newkey; },
8
+ 'setKeyPortal': (newkey) => { keyportal = newkey; },
9
+ 'checkPortal': (keyCheck) => keyCheck == keyportal,
10
+ 'auth': (req, res, next) => {
11
+ const token = req.headers['x-access-token'];
12
+ if (!token) return res.status(401).json({ auth: false, message: 'Sem token definido.' });
13
+ if (!key) return res.status(401).json({ auth: false, message: 'Sem key definida.' });
14
+ jwt.verify(token, key, (err, decoded) => {
15
+ if (err) return res.status(401).json({ auth: false, message: 'Falha na autenticação do token.' });
16
+ req.tokenId = decoded.id;
17
+ next();
18
+ });
19
+ },
20
+ 'login': (id, time) => {
21
+ if (!key) return null;
22
+ const token = jwt.sign({ id }, key, {
23
+ expiresIn: time || (60 * 30) // segundos
24
+ });
25
+ return token;
26
+ }
33
27
  }
34
28
  module.exports = utils;
package/utils/mdb.js CHANGED
@@ -1,152 +1,218 @@
1
1
  var MongoBase = require('mongodb');
2
- var ObjectID = require('mongodb').ObjectID;
2
+ var ObjectId = require('mongodb').ObjectId;
3
+ var ObjectID = ObjectId;
3
4
 
4
5
  var MDB = {
5
- status:{},
6
- clients:{}
6
+ status: {},
7
+ clients: {}
7
8
  }
8
9
 
9
- var connect= (alias,url,callback)=>{
10
- console.log('Conectando..',alias,' - url:',url);
11
- if(MDB.status[alias]){return callback(MDB.clients[alias]);}
12
- MongoBase.MongoClient.connect(url,{useUnifiedTopology: true}, (err, client)=>{
13
- if(err){return console.log('ERRO MDB -- TRACKING -- ',err);}
14
- MDB.status[alias]=true;
15
- MDB.clients[alias]=client;
16
- process.on('SIGTERM', internalStop(alias,true,'SIGTERM'));
17
- process.on('SIGINT' , internalStop(alias,true,'SIGINT'));
18
- process.on('uncaughtException', internalStop(alias,true,'uncaughtException'));
19
- console.log('Conectado com ',alias);
10
+ var connect = (alias, url, callback) => {
11
+ console.log('Conectando..', alias, ' - url:', url);
12
+ if (MDB.status[alias]) { return callback(MDB.clients[alias]); }
13
+ MongoBase.MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
14
+ if (err) { return console.log('ERRO MDB -- TRACKING -- ', err); }
15
+ MDB.status[alias] = true;
16
+ MDB.clients[alias] = client;
17
+ process.on('SIGTERM', internalStop(alias, true, 'SIGTERM'));
18
+ process.on('SIGINT', internalStop(alias, true, 'SIGINT'));
19
+ process.on('uncaughtException', internalStop(alias, true, 'uncaughtException'));
20
+ console.log('Conectado com ', alias);
20
21
  callback(client)
21
22
  });
22
23
  }
23
24
 
24
- var connectAsync = (alias, url) => new Promise(resolve => connect(alias,url,(client)=>resolve(client)));
25
+ var connectAsync = (alias, url) => new Promise(resolve => connect(alias, url, (client) => resolve(client)));
25
26
 
26
- var internalStop = (alias,finish)=>{
27
- return (code)=>{
27
+ var internalStop = (alias, finish) => {
28
+ return (code) => {
28
29
  console.log('Desconnecting...');
29
- if(!MDB.status[alias]){console.log('Mongodb OFF');return}
30
+ if (!MDB.status[alias]) { console.log('Mongodb OFF'); return }
30
31
  MDB.status[alias] = false;
31
32
  MDB.clients[alias].close();
32
- if(finish&&MDB.stopCustom){
33
- MDB.stop(alias,()=>{
34
- console.log('Mongodb',alias,'OFF');
33
+ if (finish && MDB.stopCustom) {
34
+ MDB.stop(alias, () => {
35
+ console.log('Mongodb', alias, 'OFF');
35
36
  process.exit();
36
37
  });
37
38
  }
38
- if(finish&&!MDB.stopCustom){
39
- console.log('Mongodb',alias,'OFF');
39
+ if (finish && !MDB.stopCustom) {
40
+ console.log('Mongodb', alias, 'OFF');
40
41
  process.exit();
41
42
  }
42
- if(!finish){
43
- console.log('Mongodb',alias,'OFF');
43
+ if (!finish) {
44
+ console.log('Mongodb', alias, 'OFF');
44
45
  }
45
46
  }
46
-
47
+
47
48
  }
48
-
49
49
 
50
- var stopCustom = (customCallback)=>{
51
- MDB.stopCustom=true;
52
- MDB.stop = customCallback;
50
+
51
+ var stopCustom = (customCallback) => {
52
+ MDB.stopCustom = true;
53
+ MDB.stop = customCallback;//(alias,callback)=>{}
53
54
  }
54
55
 
56
+ var genOpsUpdate = (data, params) => {
57
+ var lista = [];
58
+
59
+ for (var item of data) {
60
+ let filter = item.filter;
61
+ let update = item.update;
55
62
 
56
- function genOpsFull(data,tipo) {
63
+ var novo = params && params.newField && item[params.newField];
64
+ var remove = params && params.removeField && item[params.removeField];
65
+
66
+ if (params && params.type == 'array') {
67
+ let objArray = {}
68
+ let sub = params.rule.split('.');
69
+
70
+ update = {};
71
+
72
+ if (novo) {
73
+ delete item[params.newField];
74
+ update[sub[0]] = item;
75
+ }
76
+ else if (remove) {
77
+ delete item[params.removeField];
78
+ objArray[params.rule] = item[sub[1]];
79
+ let objRemove = {};
80
+ objRemove[sub[1]] = item[sub[1]];
81
+ update[sub[0]] = objRemove;
82
+ }
83
+ else {
84
+ objArray[params.rule] = item[sub[1]];
85
+ update[sub[0] + '.$'] = item;
86
+ }
87
+
88
+ filter = Object.assign(objArray, params.filter)
89
+ }
90
+
91
+ let objLista = {}
92
+ var upSet = { $set: update };
93
+
94
+ if (novo) {
95
+ upSet = { $addToSet: update };
96
+ }
97
+ else if (remove) {
98
+ upSet = { $pull: update };
99
+ }
100
+
101
+ objLista['updateOne'] = {
102
+ filter: filter,
103
+ update: upSet
104
+ }
105
+
106
+ lista.push(objLista)
107
+ }
108
+ return lista
109
+ }
110
+
111
+ function genOpsFull(data, tipo) {
57
112
  var lista = [];
58
- for(var x1 in data){
113
+ for (var x1 in data) {
59
114
  var objLista = {};
60
- if(typeof data[x1] != 'object'){continue;}
61
- if(tipo=='save'&&!data[x1]._id){objLista['insertOne']={document:data[x1]};}
62
- if(tipo=='save'&&data[x1]._id&&data[x1]._id.length==24){
63
- data[x1]._id=new ObjectID(data[x1]._id+'');
64
- objLista['replaceOne']={
65
- filter:{"_id" :data[x1]._id},
66
- replacement:data[x1],
67
- upsert:true
115
+ if (typeof data[x1] != 'object') { continue; }
116
+ if (tipo == 'save' && !data[x1]._id) {
117
+ objLista['insertOne'] = { document: data[x1] };
118
+ }
119
+ if (tipo == 'save' && data[x1]._id && (data[x1]._id + '').length == 24) {
120
+ data[x1]._id = new ObjectID(data[x1]._id + '');
121
+
122
+ objLista['replaceOne'] = {
123
+ filter: { "_id": data[x1]._id },
124
+ replacement: data[x1],
125
+ upsert: true
68
126
  }
69
127
  }
70
- if(tipo=='reg'){
128
+ if (tipo == 'reg' || tipo == 'regs') {
71
129
  var copyObj = Object.assign({}, data[x1]);
72
- copyObj.regId=''
73
- if(data[x1]._id){copyObj._reg.objId = data[x1]._id+'';}
130
+ copyObj.regId = ''
131
+
132
+ if (data[x1]._id) { copyObj._reg.objId = data[x1]._id + ''; }
133
+
74
134
  delete copyObj._id;
75
- objLista['insertOne']={document:copyObj};
135
+
136
+ objLista['insertOne'] = { document: copyObj };
76
137
  }
138
+
77
139
  lista.push(objLista);
78
140
  }
79
141
  return lista;
80
142
  }
81
143
 
82
- function genOps(data,tipo){
144
+
145
+ function genOps(data, tipo) {
83
146
  var lista = [];
84
147
  var regs = [];
85
- for(var x1 in data){
148
+ for (var x1 in data) {
86
149
  var objLista = {};
87
- if(typeof data[x1] != 'object'){continue;}
88
- if(tipo=='insert'&&data[x1]._id){continue;}
89
- if(tipo=='replace'&&!data[x1]._id){continue;}
90
- if(tipo=='insert'){objLista['insertOne']={document:data[x1]};}
91
- if(tipo=='replace'){
92
- data[x1]._id=new ObjectID(data[x1]._id+'');
93
- objLista['replaceOne']={
94
- filter:{"_id" :data[x1]._id},
95
- replacement:data[x1],
96
- upsert:true
150
+ if (typeof data[x1] != 'object') { continue; }
151
+ if (tipo == 'insert' && data[x1]._id) { continue; }
152
+ if (tipo == 'replace' && !data[x1]._id) { continue; }
153
+ if (tipo == 'insert') { objLista['insertOne'] = { document: data[x1] }; }
154
+ if (tipo == 'replace') {
155
+ data[x1]._id = new ObjectID(data[x1]._id + '');
156
+ objLista['replaceOne'] = {
157
+ filter: { "_id": data[x1]._id },
158
+ replacement: data[x1],
159
+ upsert: true
97
160
  }
98
161
  }
99
- if(tipo=='regs'){
162
+ if (tipo == 'regs') {
100
163
  var copyObj = Object.assign({}, data[x1]);;
101
- copyObj.regId=''
102
- if(data[x1]._id){copyObj._reg.objId = data[x1]._id+'';}
164
+ copyObj.regId = ''
165
+ if (data[x1]._id) { copyObj._reg.objId = data[x1]._id + ''; }
103
166
  delete copyObj._id;
104
- objLista['insertOne']={document:copyObj};
167
+ objLista['insertOne'] = { document: copyObj };
105
168
  }
106
169
  lista.push(objLista);
107
170
  }
108
171
  return lista;
109
172
  }
110
173
 
111
- function build(data,model,user) {
112
- var tipo = model.slice(0,3);
174
+ function build(data, model, user) {
175
+ var tipo = model.slice(0, 3);
113
176
  var time = new Date();
114
- var letra = model.slice(3,4);
115
- if(cfg.db.types.indexOf(tipo)<0){return {status:false,msg:'Tipo de Collection não definida'};}
116
- if('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(letra)<0){return {status:false,msg:'Tipo de Collection não definida'};}
117
- for(var x1 in data){
177
+ var letra = model.slice(3, 4);
178
+ // if(cfg.db.types.indexOf(tipo)<0){return {status:false,msg:'Tipo de Collection não definida'};}
179
+ if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(letra) < 0) { return { status: false, msg: 'Tipo de Collection não definida' }; }
180
+ for (var x1 in data) {
118
181
  // console.log(x1,data[x1]);
119
182
  var create = time.getTime();
120
183
  var createtext = time.toLocaleString('pt-BR');
121
- if(data[x1]._db){
122
- create = data[x1]._db.create*1;
123
- createtext = data[x1]._db.createtext+'';
184
+ if (data[x1]._db) {
185
+ create = data[x1]._db.create * 1;
186
+ createtext = data[x1]._db.createtext + '';
124
187
  }
125
- data[x1]._db={
126
- tipo:tipo,
127
- time:time.getTime(),
128
- timetext:time.toLocaleString('pt-BR').split(' ')[0],
129
- create:create*1,
130
- createtext:createtext+'',
131
- userId:user._id+'',
132
- username:user.username
188
+ data[x1]._db = {
189
+ tipo: tipo,
190
+ time: time.getTime(),
191
+ timetext: time.toLocaleString('pt-BR').split(' ')[0],
192
+ create: create * 1,
193
+ createtext: createtext + '',
194
+ userId: user._id + '',
195
+ username: user.username
133
196
  };
134
- var objId = data[x1]._reg&&data[x1]._reg.objId?data[x1]._reg.objId:'';
135
- data[x1]._reg={
136
- regId:time.getTime()+user._id+'',
137
- collection:model,
138
- objId:objId,
139
- reg:'reg'+model.slice(0,1).toUpperCase()+model.slice(1)
197
+ var objId = data[x1]._reg && data[x1]._reg.objId ? data[x1]._reg.objId : '';
198
+ data[x1]._reg = {
199
+ regId: time.getTime() + user._id + '',
200
+ collection: model,
201
+ objId: objId,
202
+ reg: 'reg' + model.slice(0, 1).toUpperCase() + model.slice(1)
140
203
  };
141
204
  }
142
205
  return data;
143
206
  }
144
207
 
145
208
  module.exports = {
146
- connect:connect,
147
- connectAsync:connectAsync,
148
- stopCustom:stopCustom,
149
- build:build,
150
- genOps:genOps,
151
- genOpsFull:genOpsFull
209
+ ObjectId,
210
+ ObjectID,
211
+ connect,
212
+ connectAsync,
213
+ stopCustom,
214
+ build,
215
+ genOps,
216
+ genOpsFull,
217
+ genOpsUpdate
152
218
  };
package/utils/querys.js CHANGED
@@ -1,3 +1,5 @@
1
+ const mdb = require('./mdb');
2
+
1
3
  var querys = {
2
4
  'findAsync': (db, collection, filter) => new Promise(resolve => db.collection(collection).find(filter).toArray((err, result) => resolve(result))),
3
5
  'findLimitAsync': (db, collection, filter, limit) => new Promise(resolve => db.collection(collection).find(filter).limit(limit).toArray((err, result) => resolve(result))),
@@ -43,6 +45,15 @@ var querys = {
43
45
  });
44
46
 
45
47
  }),
48
+ 'updateFilterAsync': (db, collection, data, param) => new Promise(resolve => {
49
+ var listaOps = mdb.genOpsUpdate(data, param);
50
+ console.log(listaOps)
51
+ db.collection(collection).bulkWrite(listaOps, (err, result) => {
52
+ if (err) { console.log('Erro bulkwrite cad: ', err); }
53
+ var result = result.result;
54
+ resolve({ status: true, result });
55
+ });
56
+ }),
46
57
  'updateManyAsync':(db,collection,data) => new Promise(resolve=>{
47
58
  var listaOps = mdb.genOpsFull(data, 'save');
48
59
  db.collection(collection).bulkWrite(listaOps, (err, result) => {
package/utils/tools.js CHANGED
@@ -19,6 +19,15 @@ var tools = {
19
19
  resolve({status:false,error});
20
20
  });
21
21
  }),
22
+ 'get': (url, headers, config) => new Promise(resolve => {
23
+ axios.get(url, Object.assign({ headers: headers }, config))
24
+ .then((response) => {
25
+ resolve({ status: true, data: response.data });
26
+ })
27
+ .catch((error) => {
28
+ resolve({ status: false, error });
29
+ });
30
+ }),
22
31
  'psql':(acesso,query)=> new Promise(resolve=>{
23
32
  var client = new Client(acesso)
24
33
  client.connect()
@@ -30,7 +39,54 @@ var tools = {
30
39
  }
31
40
  client.end()
32
41
  })
33
- })
42
+ }),
43
+ /**
44
+ * @param {number} milliseconds Valor em milisegundos para ser convertido
45
+ * @returns Retorna uma string no formato **0h 0m 0s** ou retorna **--** em caso de erro
46
+ */
47
+ 'findDistance': (posA, posB) => {
48
+ let rad;
49
+ function deg2rad(deg) {
50
+ rad = deg * Math.PI / 180; // radians = degrees * pi/180
51
+ return rad;
52
+ }
53
+ function round(x) {
54
+ return Math.round(x * 1000) / 1000;
55
+ }
56
+ var Rm = 3961; // mean radius of the earth (miles) at 39 degrees from the equator
57
+ var Rk = 6373; // mean radius of the earth (km) at 39 degrees from the equator
58
+ var t1, n1, t2, n2, lat1, lon1, lat2, lon2, dlat, dlon, a, c, dm, dk, mi, km;
59
+
60
+ // get values for lat1, lon1, lat2, and lon2
61
+ t1 = posA.lat;
62
+ n1 = posA.lng;
63
+ t2 = posB.lat;
64
+ n2 = posB.lng;
65
+
66
+ // convert coordinates to radians
67
+ lat1 = deg2rad(t1);
68
+ lon1 = deg2rad(n1);
69
+ lat2 = deg2rad(t2);
70
+ lon2 = deg2rad(n2);
71
+
72
+ // find the differences between the coordinates
73
+ dlat = lat2 - lat1;
74
+ dlon = lon2 - lon1;
75
+
76
+ // here's the heavy lifting
77
+ a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2), 2);
78
+ c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); // great circle distance in radians
79
+ dm = c * Rm; // great circle distance in miles
80
+ dk = c * Rk; // great circle distance in km
81
+
82
+ // round the results down to the nearest 1/1000
83
+ mi = round(dm);
84
+ km = round(dk);
85
+
86
+ // display the result
87
+ // frm.mi.value = mi;
88
+ return km;
89
+ }
34
90
  }
35
91
 
36
92
  module.exports = tools;