molly-db 1.0.5 → 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,21 +22,20 @@ 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`);
29
28
 
30
29
  this.worker = new worker.Worker(
31
- `${__dirname}/module/_worker_`,{
30
+ `${__dirname}/module/_worker_.js`,{
32
31
  env: worker.SHARE_ENV,
33
32
  workerData: this
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 ){
@@ -63,9 +105,10 @@ function match( _params ){
63
105
  const regex = new RegExp(crypto.slugify(_params.target),'gi');
64
106
  const target = crypto.slugify(x);
65
107
  if( regex.test(target) ) result.push(x);
66
- }).slice(
108
+ });
109
+ return result.map(x=>JSON.parse(x)).slice(
67
110
  _params.offset, Number(_params.offset)+Number(_params.length)
68
- ); return result.map(x=>JSON.parse(x));
111
+ );
69
112
  }
70
113
 
71
114
  function hash( _params ){
@@ -73,126 +116,171 @@ function hash( _params ){
73
116
  db[_params.db][_params.table].map((x)=>{
74
117
  const regex = new RegExp(_params.target,'gi');
75
118
  if( regex.test(x) ) result.push(x);
76
- }).slice(
119
+ });
120
+ return result.map(x=>JSON.parse(x)).slice(
77
121
  _params.offset, Number(_params.offset)+Number(_params.length)
78
- ); return result.map(x=>JSON.parse(x));
122
+ );
79
123
  }
80
124
 
81
125
  /* --------------------------------------------------------------------------------------- */
82
126
 
83
127
  function shift( _params ){
84
- const result = db[_params.db][_params.table].shift();
85
- modifyDB( _params.db,_params.table ); return result;
128
+ const result = db[_params.db][_params.table].shift(); save( _params ); return result;
86
129
  }
87
130
 
88
131
  function pop( _params ){
89
- const result = db[_params.db][_params.table].pop();
90
- modifyDB( _params.db,_params.table ); return result; return result;
132
+ const result = db[_params.db][_params.table].pop(); save( _params ); return result;
91
133
  }
92
134
 
93
135
  /* --------------------------------------------------------------------------------------- */
94
136
 
95
137
  async function push( _params ){
96
138
 
97
- const body = await getBody();
98
139
  db[_params.db][_params.table].push( body );
99
140
 
100
- modifyDB( _params.db,_params.table );
101
- return {
141
+ save( _params ); return [{
102
142
  database: _params.db,
103
143
  table: _params.table,
104
144
  status: 'pushed'
105
- };
145
+ }];
106
146
 
107
147
  }
108
148
 
109
149
  async function splice( _params ){
110
150
 
111
- const body = await getBody();
112
151
  db[_params.db][_params.table].splice(
113
152
  _params.offset,_params.length,body
114
153
  );
115
154
 
116
- modifyDB( _params.db,_params.table );
117
- return {
155
+ save( _params ); return [{
118
156
  database: _params.db,
119
157
  table: _params.table,
120
158
  status: 'spliced'
121
- };
159
+ }];
122
160
  }
123
161
 
124
162
  async function unshift( _params ){
125
163
 
126
- const body = await getBody();
127
164
  db[_params.db][_params.table].unshift( body );
128
165
 
129
- modifyDB( _params.db,_params.table );
130
- return {
166
+ save( _params ); return [{
131
167
  database: _params.db,
132
168
  table: _params.table,
133
169
  status: 'unshifted'
134
- };
170
+ }];
135
171
  }
136
172
 
137
173
  /* --------------------------------------------------------------------------------------- */
138
174
 
139
- function addDB( _params ){
140
-
141
- const init = `${query.path}/_init_.json`;
175
+ async function update( _params ){
142
176
 
143
- db._init_.DB.push({
144
- name: _params.db,
145
- tables: []
177
+ const index = db[_params.db][_params.table].findIndex(x=>{
178
+ const regex = new RegExp(_params.target,'gi');
179
+ return regex.test(x);
146
180
  });
147
181
 
148
- db[_params.db] = new Array();
149
- fs.writeFileSync( init,JSON.stringify(db._init_) );
182
+ if( !(index<0) )
183
+ db[_params.db][_params.table].splice( index,1,body );
150
184
 
151
- return {
185
+ save( _params ); return [{
152
186
  database: _params.db,
153
- status: 'DB added'
154
- };
155
-
187
+ table: _params.table,
188
+ status: 'udated'
189
+ }];
156
190
  }
157
191
 
158
- function removeDB( _params ){
192
+ async function remove( _params ){
159
193
 
160
- const init = `${query.path}/_init_.json`;
161
- const i = db._init_.DB.findIndex(x=>{
162
- return x.name == _params.db
163
- });
194
+ const index = db[_params.db][_params.table].findIndex(x=>{
195
+ const regex = new RegExp(_params.target,'gi');
196
+ return regex.test(x);
197
+ });
164
198
 
165
- db._init_.DB[i].tables.forEach(x=>{
166
- const path = `${query.path}/${x}.json`;
167
- fs.unlinkSync(path);
168
- }); db._init_.DB.splice(i,1);
199
+ if( !(index<0) )
200
+ db[_params.db][_params.table].splice( index,1 );
201
+
202
+ save( _params ); return [{
203
+ database: _params.db,
204
+ table: _params.table,
205
+ status: 'removed'
206
+ }];
207
+ }
169
208
 
170
- db[_params.db] = new Array();
171
- fs.writeFileSync( init,JSON.stringify(db._init_) );
209
+ async function save( _params ){
172
210
 
173
- return {
211
+ modifyDB( _params.db,_params.table );
212
+ return [{
174
213
  database: _params.db,
175
214
  table: _params.table,
176
- status: 'DB deleted'
177
- };
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
+ });
178
230
 
231
+ db[_params.db] = new Array();
232
+ fs.writeFileSync( init,JSON.stringify(db._init_) );
233
+
234
+ return [{
235
+ database: _params.db,
236
+ status: 'DB added'
237
+ }];
238
+
239
+ } catch(e) { }
179
240
  }
180
241
 
181
- function modifyDB( _name, _table ){
242
+ function removeDB( _params ){
243
+ try{
182
244
 
183
- const init = `${query.path}/_init_.json`;
184
- 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
+ }];
185
263
 
186
- fs.writeFileSync( init,JSON.stringify(db._init_) );
264
+ } catch(e) { }
265
+ }
187
266
 
188
- try {
189
- const length = db[_name][_table].length;
190
- if( length>0 ) encryptDB( _name, _table, path );
191
- else fs.writeFileSync( path,'' );
192
- } catch(e) {
193
- fs.unlinkSync( path );
194
- }
267
+ function modifyDB( _name, _table ){
268
+ try{
195
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) { }
196
284
  }
197
285
 
198
286
  /* --------------------------------------------------------------------------------------- */
@@ -211,13 +299,12 @@ function addTable( _params ){
211
299
  }); db._init_.DB[i].tables.push(_params.table);
212
300
 
213
301
  db[_params.db][_params.table] = new Array();
214
- modifyDB( _params.db,_params.table );
215
302
 
216
- return {
303
+ return [{
217
304
  database: _params.db,
218
305
  table: _params.table,
219
306
  status: 'table added'
220
- };
307
+ }];
221
308
 
222
309
  }
223
310
 
@@ -233,28 +320,42 @@ function removeTable( _params ){
233
320
 
234
321
  db._init_.DB[i].tables.splice(j,1);
235
322
  delete db[_params.db][_params.table];
236
- modifyDB( _params.db,_params.table );
237
323
 
238
- return {
324
+ return [{
239
325
  database: _params.db,
240
326
  table: _params.table,
241
327
  status: 'table removed'
242
- };
328
+ }];
243
329
 
244
330
  }
245
331
 
246
332
  /* --------------------------------------------------------------------------------------- */
247
333
 
248
- (async()=>{
249
- 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
+ }
250
340
 
251
- const api = url.parse( req.url,true );
252
- const params = api.query;
341
+ /* --------------------------------------------------------------------------------------- */
342
+
343
+ (async ()=>{
344
+ try{
345
+
346
+ body = await getBody();
347
+ params = await validate(params);
253
348
 
254
349
  /* Find Api */
255
350
  if( api.pathname == '/list' ) json( await list(params) )
256
351
  else if( api.pathname == '/hash' ) json( await hash(params) )
257
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) )
258
359
 
259
360
  /* Remove Api */
260
361
  else if( api.pathname == '/pop' ) json( await pop(params) )
@@ -275,7 +376,7 @@ function removeTable( _params ){
275
376
 
276
377
  else error('Oops something went wrong');
277
378
 
278
- } catch(e) { error(e); }
379
+ } catch(e) { error(e?.message||e); }
279
380
  })();
280
381
 
281
382
  /* --------------------------------------------------------------------------------------- */
@@ -9,34 +9,41 @@ 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
  /* --------------------------------------------------------------------------------------- */
28
31
 
29
32
  (()=>{
30
33
  try{
31
- console.log('molly-db is running, please wait');
32
34
  http.createServer( app ).listen( query.port,()=>{
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.5",
4
+ "version": "1.0.9",
5
5
  "name": "molly-db",
6
6
  "author": "bececrazy",
7
7
  "scripts": {