molly-db 1.0.7 → 1.0.9

Sign up to get free protection for your applications and to get access to all the features.
package/main.js CHANGED
@@ -22,7 +22,6 @@ class molly_db{
22
22
  if( opt.pass )
23
23
  this.pass = opt.pass;
24
24
  this.port = opt.port || 27017;
25
- this.type = opt.type || 'local';
26
25
  this.path = opt.path.replace(/^\./,process.cwd());
27
26
 
28
27
  if( this.worker ) return console.log(`server is running`);
@@ -34,9 +33,9 @@ class molly_db{
34
33
  }
35
34
  );
36
35
 
37
- this.worker.on('exit',(err)=>{ });
38
- this.worker.on('error',(err)=>{ });
39
- this.worker.on('message',(msg)=>{ console.log(msg); response(); });
36
+ this.worker.on('exit',(err)=>{ console.log(err); reject() });
37
+ this.worker.on('error',(err)=>{ console.log(err); reject() });
38
+ this.worker.on('message',(msg)=>{ console.log(msg); response() });
40
39
  });
41
40
  }
42
41
 
@@ -28,19 +28,23 @@ const JsonFormatter = {
28
28
  /* --------------------------------------------------------------------------------------- */
29
29
 
30
30
  output.slugify = (str)=>{
31
- const map = {
32
- 'c' : 'ç',
33
- 'n' : 'ñ',
34
- 'e' : 'é|è|ê|ë',
35
- 'i' : 'í|ì|î|ï',
36
- 'u' : 'ú|ù|û|ü',
37
- 'o' : 'ó|ò|ô|õ|ö',
38
- 'a' : 'á|à|ã|â|ä',
39
- '' : /\s+|\W+/,
40
- };
41
- for (var pattern in map) {
42
- str=str.replace( new RegExp(map[pattern],'gi' ), pattern);
43
- } return str.toLowerCase();
31
+ [
32
+ ['c','ç'],
33
+ ['n','ñ'],
34
+ ['e','é|è|ê|ë'],
35
+ ['i','í|ì|î|ï'],
36
+ ['u','ú|ù|û|ü'],
37
+ ['o','ó|ò|ô|õ|ö'],
38
+ ['a','á|à|ã|â|ä'],
39
+ ['' ,/\s+|\W+/,]
40
+ ].map(x=>{
41
+ const regex = new RegExp(x[1],'gi');
42
+ str = str.replace( regex,x[0] );
43
+ }); return str.toLowerCase();
44
+ }
45
+
46
+ output.hash = (data,nonce)=>{
47
+ return crypto.SHA256(Math.random+data+nonce).toString();
44
48
  }
45
49
 
46
50
  output.encrypt = ( _message,_password )=>{
package/module/_init_.js CHANGED
@@ -43,7 +43,8 @@ function fillDB( _db, _table, _path ){
43
43
 
44
44
  const DB = db._init_.DB[i];
45
45
  const name = DB.name;
46
-
46
+ delete db[name];
47
+
47
48
  db[name] = new Object();
48
49
 
49
50
  for( var j in DB.tables ){
@@ -1,13 +1,14 @@
1
1
 
2
- function text( _data ){
3
- res.writeHead(200,{'contetn-type':'text/plain'});
4
- res.end( _data );
5
- }
2
+ const api = url.parse( req.url,true );
3
+ let params = api.query;
4
+ let body = undefined;
5
+
6
+ /* --------------------------------------------------------------------------------------- */
6
7
 
7
8
  function error( _error ){
8
- res.writeHead(200,{'contetn-type':'text/plain'});
9
- res.end(`error: ${_error.message}`);
10
- console.log(_error);
9
+ res.writeHead(404,{'contetn-type':'application/json'});
10
+ res.end(JSON.stringify([{ status:'error', message:_error }]));
11
+ console.log( _error,req.url );
11
12
  }
12
13
 
13
14
  function json( _data ){
@@ -19,11 +20,22 @@ function json( _data ){
19
20
 
20
21
  function getBody(){
21
22
  return new Promise((response,reject)=>{
22
- if( req.method == 'POST' ){
23
- const data = new Array();
24
- req.on('data',(chunk)=>{ data.push(chunk); });
25
- req.on('close',()=>{ response( Buffer.concat(data).toString() ); });
26
- } else { reject() }
23
+ try{
24
+ if( req.method == 'POST' ){
25
+ const data = new Array();
26
+ req.on('data',(chunk)=>{ data.push(chunk); });
27
+ req.on('close',()=>{ try{
28
+ const buff = Buffer.concat(data).toString();
29
+ const object = JSON.parse(buff);
30
+ const date = Date.now();
31
+
32
+ if( !object.hash )
33
+ object.hash = crypto.hash( date,0 );
34
+
35
+ response(JSON.stringify(object));
36
+ } catch(e) { response(false) } });
37
+ } else { response(true) }
38
+ } catch(e) { response(false) }
27
39
  });
28
40
  }
29
41
 
@@ -49,6 +61,36 @@ function encryptDB( _db,_table, _path ){
49
61
  });
50
62
  }
51
63
 
64
+ function validate( _params ){
65
+ return new Promise((response,reject)=>{
66
+
67
+ let validator = false;
68
+
69
+ const vtb = (key)=>{ return db._init_.DB.some(x=>{ return x.tables.join().match(key); }) }
70
+ const vdb = (key)=>{ return db._init_.DB.some(x=>{ return x.name == key; }) }
71
+
72
+ validator = [
73
+ [!body, {status:'error',message:'invalid data'}],
74
+ [!_params?.db, {status:'error',message:'no db name added'}],
75
+ [!_params?.table, {status:'error',message:'no table name added'}]
76
+ ].some(x=>{ if(x[0]) reject(x[1]); return x[0];}); if(validator) return 0;
77
+
78
+ validator = [
79
+ [!vdb(_params?.db), {status:'error',message:`no db called ${_params.db} exist`}],
80
+ [!vtb(_params?.table), {status:'error',message:`no table called ${_params.table} exist`}]
81
+ ].some(x=>{ if(x[0]) reject(x[1]); return x[0];}); if(validator) return 0;
82
+
83
+ validator = [
84
+ [ !_params.offset, '_params.offset = 0' ],
85
+ [ !_params.target, '_params.target = ""' ],
86
+ [ !_params.length, '_params.length = 100' ],
87
+ ].map(x=>{ if(x[0]) eval(x[1]) });
88
+
89
+ response(_params);
90
+
91
+ });
92
+ }
93
+
52
94
  /* --------------------------------------------------------------------------------------- */
53
95
 
54
96
  function list( _params ){
@@ -83,118 +125,162 @@ function hash( _params ){
83
125
  /* --------------------------------------------------------------------------------------- */
84
126
 
85
127
  function shift( _params ){
86
- const result = db[_params.db][_params.table].shift();
87
- modifyDB( _params.db,_params.table ); return result;
128
+ const result = db[_params.db][_params.table].shift(); save( _params ); return result;
88
129
  }
89
130
 
90
131
  function pop( _params ){
91
- const result = db[_params.db][_params.table].pop();
92
- modifyDB( _params.db,_params.table ); return result; return result;
132
+ const result = db[_params.db][_params.table].pop(); save( _params ); return result;
93
133
  }
94
134
 
95
135
  /* --------------------------------------------------------------------------------------- */
96
136
 
97
137
  async function push( _params ){
98
138
 
99
- const body = await getBody();
100
139
  db[_params.db][_params.table].push( body );
101
140
 
102
- modifyDB( _params.db,_params.table );
103
- return {
141
+ save( _params ); return [{
104
142
  database: _params.db,
105
143
  table: _params.table,
106
144
  status: 'pushed'
107
- };
145
+ }];
108
146
 
109
147
  }
110
148
 
111
149
  async function splice( _params ){
112
150
 
113
- const body = await getBody();
114
151
  db[_params.db][_params.table].splice(
115
152
  _params.offset,_params.length,body
116
153
  );
117
154
 
118
- modifyDB( _params.db,_params.table );
119
- return {
155
+ save( _params ); return [{
120
156
  database: _params.db,
121
157
  table: _params.table,
122
158
  status: 'spliced'
123
- };
159
+ }];
124
160
  }
125
161
 
126
162
  async function unshift( _params ){
127
163
 
128
- const body = await getBody();
129
164
  db[_params.db][_params.table].unshift( body );
130
165
 
131
- modifyDB( _params.db,_params.table );
132
- return {
166
+ save( _params ); return [{
133
167
  database: _params.db,
134
168
  table: _params.table,
135
169
  status: 'unshifted'
136
- };
170
+ }];
137
171
  }
138
172
 
139
173
  /* --------------------------------------------------------------------------------------- */
140
174
 
141
- function addDB( _params ){
142
-
143
- const init = `${query.path}/_init_.json`;
175
+ async function update( _params ){
144
176
 
145
- db._init_.DB.push({
146
- name: _params.db,
147
- tables: []
177
+ const index = db[_params.db][_params.table].findIndex(x=>{
178
+ const regex = new RegExp(_params.target,'gi');
179
+ return regex.test(x);
148
180
  });
149
181
 
150
- db[_params.db] = new Array();
151
- fs.writeFileSync( init,JSON.stringify(db._init_) );
182
+ if( !(index<0) )
183
+ db[_params.db][_params.table].splice( index,1,body );
152
184
 
153
- return {
185
+ save( _params ); return [{
154
186
  database: _params.db,
155
- status: 'DB added'
156
- };
157
-
187
+ table: _params.table,
188
+ status: 'udated'
189
+ }];
158
190
  }
159
191
 
160
- function removeDB( _params ){
192
+ async function remove( _params ){
161
193
 
162
- const init = `${query.path}/_init_.json`;
163
- const i = db._init_.DB.findIndex(x=>{
164
- return x.name == _params.db
165
- });
194
+ const index = db[_params.db][_params.table].findIndex(x=>{
195
+ const regex = new RegExp(_params.target,'gi');
196
+ return regex.test(x);
197
+ });
166
198
 
167
- db._init_.DB[i].tables.forEach(x=>{
168
- const path = `${query.path}/${x}.json`;
169
- fs.unlinkSync(path);
170
- }); db._init_.DB.splice(i,1);
199
+ if( !(index<0) )
200
+ db[_params.db][_params.table].splice( index,1 );
171
201
 
172
- db[_params.db] = new Array();
173
- fs.writeFileSync( init,JSON.stringify(db._init_) );
202
+ save( _params ); return [{
203
+ database: _params.db,
204
+ table: _params.table,
205
+ status: 'removed'
206
+ }];
207
+ }
174
208
 
175
- return {
209
+ async function save( _params ){
210
+
211
+ modifyDB( _params.db,_params.table );
212
+ return [{
176
213
  database: _params.db,
177
214
  table: _params.table,
178
- status: 'DB deleted'
179
- };
215
+ status: 'saved'
216
+ }];
217
+ }
218
+
219
+ /* --------------------------------------------------------------------------------------- */
220
+
221
+ function addDB( _params ){
222
+ try{
223
+
224
+ const init = `${query.path}/_init_.json`;
225
+
226
+ db._init_.DB.push({
227
+ name: _params.db,
228
+ tables: []
229
+ });
230
+
231
+ db[_params.db] = new Array();
232
+ fs.writeFileSync( init,JSON.stringify(db._init_) );
180
233
 
234
+ return [{
235
+ database: _params.db,
236
+ status: 'DB added'
237
+ }];
238
+
239
+ } catch(e) { }
181
240
  }
182
241
 
183
- function modifyDB( _name, _table ){
242
+ function removeDB( _params ){
243
+ try{
184
244
 
185
- const init = `${query.path}/_init_.json`;
186
- const path = `${query.path}/${_table}.json`;
245
+ const init = `${query.path}/_init_.json`;
246
+ const i = db._init_.DB.findIndex(x=>{
247
+ return x.name == _params.db
248
+ });
249
+
250
+ db._init_.DB[i].tables.forEach(x=>{
251
+ const path = `${query.path}/${x}.json`;
252
+ fs.unlinkSync(path);
253
+ }); db._init_.DB.splice(i,1);
254
+
255
+ db[_params.db] = new Array();
256
+ fs.writeFileSync( init,JSON.stringify(db._init_) );
257
+
258
+ return [{
259
+ database: _params.db,
260
+ table: _params.table,
261
+ status: 'DB deleted'
262
+ }];
187
263
 
188
- fs.writeFileSync( init,JSON.stringify(db._init_) );
264
+ } catch(e) { }
265
+ }
189
266
 
190
- try {
191
- const length = db[_name][_table].length;
192
- if( length>0 ) encryptDB( _name, _table, path );
193
- else fs.writeFileSync( path,'' );
194
- } catch(e) {
195
- fs.unlinkSync( path );
196
- }
267
+ function modifyDB( _name, _table ){
268
+ try{
197
269
 
270
+ const init = `${query.path}/_init_.json`;
271
+ const path = `${query.path}/${_table}.json`;
272
+
273
+ fs.writeFileSync( init,JSON.stringify(db._init_) );
274
+
275
+ try {
276
+ const length = db[_name][_table].length;
277
+ if( length>0 ) encryptDB( _name, _table, path );
278
+ else fs.writeFileSync( path,'' );
279
+ } catch(e) {
280
+ fs.unlinkSync( path );
281
+ }
282
+
283
+ } catch(e) { }
198
284
  }
199
285
 
200
286
  /* --------------------------------------------------------------------------------------- */
@@ -213,13 +299,12 @@ function addTable( _params ){
213
299
  }); db._init_.DB[i].tables.push(_params.table);
214
300
 
215
301
  db[_params.db][_params.table] = new Array();
216
- modifyDB( _params.db,_params.table );
217
302
 
218
- return {
303
+ return [{
219
304
  database: _params.db,
220
305
  table: _params.table,
221
306
  status: 'table added'
222
- };
307
+ }];
223
308
 
224
309
  }
225
310
 
@@ -235,28 +320,42 @@ function removeTable( _params ){
235
320
 
236
321
  db._init_.DB[i].tables.splice(j,1);
237
322
  delete db[_params.db][_params.table];
238
- modifyDB( _params.db,_params.table );
239
323
 
240
- return {
324
+ return [{
241
325
  database: _params.db,
242
326
  table: _params.table,
243
327
  status: 'table removed'
244
- };
328
+ }];
245
329
 
246
330
  }
247
331
 
248
332
  /* --------------------------------------------------------------------------------------- */
249
333
 
250
- (async()=>{
251
- try{
334
+ function refresh( _params ){
335
+ return new Promise((response,reject)=>{
336
+ _init_().then(()=>{ response([{status: 'done'}]) })
337
+ .catch((e)=>{ reject([{status:'error',message:e.message}]) });
338
+ });
339
+ }
252
340
 
253
- const api = url.parse( req.url,true );
254
- const params = api.query;
341
+ /* --------------------------------------------------------------------------------------- */
342
+
343
+ (async ()=>{
344
+ try{
345
+
346
+ body = await getBody();
347
+ params = await validate(params);
255
348
 
256
349
  /* Find Api */
257
350
  if( api.pathname == '/list' ) json( await list(params) )
258
351
  else if( api.pathname == '/hash' ) json( await hash(params) )
259
352
  else if( api.pathname == '/match' ) json( await match(params) )
353
+ else if( api.pathname == '/update' ) json( await update(params) )
354
+
355
+ /* Save Api */
356
+ else if( api.pathname == '/save' ) json( await save(params) )
357
+ else if( api.pathname == '/remove' ) json( await remove(params) )
358
+ else if( api.pathname == '/refresh' ) json( await refresh(params) )
260
359
 
261
360
  /* Remove Api */
262
361
  else if( api.pathname == '/pop' ) json( await pop(params) )
@@ -277,7 +376,7 @@ function removeTable( _params ){
277
376
 
278
377
  else error('Oops something went wrong');
279
378
 
280
- } catch(e) { error(e); }
379
+ } catch(e) { error(e?.message||e); }
281
380
  })();
282
381
 
283
382
  /* --------------------------------------------------------------------------------------- */
@@ -9,19 +9,22 @@ const fs = require('fs');
9
9
 
10
10
  const query = worker.workerData;
11
11
  const db = new Object();
12
-
13
12
  /* --------------------------------------------------------------------------------------- */
14
13
 
15
- function app(req,res){
16
- eval( fs.readFileSync(`${__dirname}/_server_.js`).toString() );
14
+ function _init_(){
15
+ return new Promise((response,reject)=>{
16
+ try{
17
+ eval( fs.readFileSync(`${__dirname}/_init_.js`).toString() );
18
+ } catch(e){ console.log(e); }
19
+ });
17
20
  }
18
21
 
19
22
  /* --------------------------------------------------------------------------------------- */
20
23
 
21
- function _init_(){
22
- return new Promise((response,reject)=>{
23
- eval( fs.readFileSync(`${__dirname}/_init_.js`).toString() );
24
- });
24
+ function app(req,res){
25
+ try{
26
+ eval( fs.readFileSync(`${__dirname}/_server_.js`).toString() );
27
+ } catch(e) { console.log(e) }
25
28
  }
26
29
 
27
30
  /* --------------------------------------------------------------------------------------- */
@@ -29,14 +32,18 @@ function _init_(){
29
32
  (()=>{
30
33
  try{
31
34
  http.createServer( app ).listen( query.port,()=>{
32
- console.log('molly-db is running, please wait');
35
+ console.log('molly-db cluster is running, please wait');
33
36
  _init_().then(()=>{
34
- worker.parentPort.postMessage(
35
- `server started -> http://localhost:${query.port}`
36
- );
37
+ worker.parentPort.postMessage({
38
+ protocol: 'HTTP',
39
+ status: 'started',
40
+ workerID: process.pid,
41
+ msg: 'molly-db is running',
42
+ server: `http://localhost:${query.port}`,
43
+ });
37
44
  }).catch(e=>{ process.exit(1); });
38
45
  });
39
- } catch(e) { process.exit(1); }
46
+ } catch(e) {}
40
47
  })();
41
48
 
42
49
  /* --------------------------------------------------------------------------------------- */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "license": "MIT",
3
3
  "main": "main.js",
4
- "version": "1.0.7",
4
+ "version": "1.0.9",
5
5
  "name": "molly-db",
6
6
  "author": "bececrazy",
7
7
  "scripts": {