molly-db 1.0.6 → 1.0.10

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.
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,15 @@
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
+ let parse = api;
6
+
7
+ /* --------------------------------------------------------------------------------------- */
6
8
 
7
9
  function error( _error ){
8
- res.writeHead(200,{'contetn-type':'text/plain'});
9
- res.end(`error: ${_error.message}`);
10
- console.log(_error);
10
+ res.writeHead(404,{'contetn-type':'application/json'});
11
+ res.end(JSON.stringify([{ status:'error', message:_error }]));
12
+ console.log( _error,req.url );
11
13
  }
12
14
 
13
15
  function json( _data ){
@@ -19,11 +21,22 @@ function json( _data ){
19
21
 
20
22
  function getBody(){
21
23
  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() }
24
+ try{
25
+ if( req.method == 'POST' ){
26
+ const data = new Array();
27
+ req.on('data',(chunk)=>{ data.push(chunk); });
28
+ req.on('close',()=>{ try{
29
+ const buff = Buffer.concat(data).toString();
30
+ const object = JSON.parse(buff);
31
+ const date = Date.now();
32
+
33
+ if( !object.hash )
34
+ object.hash = crypto.hash( date,0 );
35
+
36
+ response(JSON.stringify(object));
37
+ } catch(e) { response(false) } });
38
+ } else { response(true) }
39
+ } catch(e) { response(false) }
27
40
  });
28
41
  }
29
42
 
@@ -49,6 +62,38 @@ function encryptDB( _db,_table, _path ){
49
62
  });
50
63
  }
51
64
 
65
+ function validate( _params ){
66
+ return new Promise((response,reject)=>{
67
+
68
+ let validator = false;
69
+
70
+ const vdb = (key)=>{ return db._init_.DB.some(x=>{ return x.name == key; }) }
71
+ const vtb = (key)=>{ return db._init_.DB.some(x=>{ return x.tables.join().match(key); }) }
72
+
73
+ validator = [
74
+ [ !_params.offset, '_params.offset = 0' ],
75
+ [ !_params.target, '_params.target = ""' ],
76
+ [ !_params.length, '_params.length = 100' ],
77
+ ].every(x=>{ if(x[0]) eval(x[1]); return true; });
78
+
79
+ validator = [
80
+ [!body, {status:'error',message:'invalid data'}],
81
+ [!_params?.db, {status:'error',message:'no db name added'}],
82
+ [!_params?.table, {status:'error',message:'no table name added'}]
83
+ ].some(x=>{ if(x[0]) reject(x[1]); return x[0];}); if(validator) return 0;
84
+
85
+ if( !(/table|db/gi).test(parse.pathname) ){
86
+ validator = [
87
+ [!vdb(_params?.db), {status:'error',message:`no db called ${_params.db} exist`}],
88
+ [!vtb(_params?.table), {status:'error',message:`no table called ${_params.table} exist`}]
89
+ ].some(x=>{ if(x[0]) reject(x[1]); return x[0];}); if(validator) return 0;
90
+ }
91
+
92
+ response(_params);
93
+
94
+ });
95
+ }
96
+
52
97
  /* --------------------------------------------------------------------------------------- */
53
98
 
54
99
  function list( _params ){
@@ -83,118 +128,162 @@ function hash( _params ){
83
128
  /* --------------------------------------------------------------------------------------- */
84
129
 
85
130
  function shift( _params ){
86
- const result = db[_params.db][_params.table].shift();
87
- modifyDB( _params.db,_params.table ); return result;
131
+ const result = db[_params.db][_params.table].shift(); save( _params ); return result;
88
132
  }
89
133
 
90
134
  function pop( _params ){
91
- const result = db[_params.db][_params.table].pop();
92
- modifyDB( _params.db,_params.table ); return result; return result;
135
+ const result = db[_params.db][_params.table].pop(); save( _params ); return result;
93
136
  }
94
137
 
95
138
  /* --------------------------------------------------------------------------------------- */
96
139
 
97
140
  async function push( _params ){
98
141
 
99
- const body = await getBody();
100
142
  db[_params.db][_params.table].push( body );
101
143
 
102
- modifyDB( _params.db,_params.table );
103
- return {
144
+ save( _params ); return [{
104
145
  database: _params.db,
105
146
  table: _params.table,
106
147
  status: 'pushed'
107
- };
148
+ }];
108
149
 
109
150
  }
110
151
 
111
152
  async function splice( _params ){
112
153
 
113
- const body = await getBody();
114
154
  db[_params.db][_params.table].splice(
115
155
  _params.offset,_params.length,body
116
156
  );
117
157
 
118
- modifyDB( _params.db,_params.table );
119
- return {
158
+ save( _params ); return [{
120
159
  database: _params.db,
121
160
  table: _params.table,
122
161
  status: 'spliced'
123
- };
162
+ }];
124
163
  }
125
164
 
126
165
  async function unshift( _params ){
127
166
 
128
- const body = await getBody();
129
167
  db[_params.db][_params.table].unshift( body );
130
168
 
131
- modifyDB( _params.db,_params.table );
132
- return {
169
+ save( _params ); return [{
133
170
  database: _params.db,
134
171
  table: _params.table,
135
172
  status: 'unshifted'
136
- };
173
+ }];
137
174
  }
138
175
 
139
176
  /* --------------------------------------------------------------------------------------- */
140
177
 
141
- function addDB( _params ){
142
-
143
- const init = `${query.path}/_init_.json`;
178
+ async function update( _params ){
144
179
 
145
- db._init_.DB.push({
146
- name: _params.db,
147
- tables: []
180
+ const index = db[_params.db][_params.table].findIndex(x=>{
181
+ const regex = new RegExp(_params.target,'gi');
182
+ return regex.test(x);
148
183
  });
149
184
 
150
- db[_params.db] = new Array();
151
- fs.writeFileSync( init,JSON.stringify(db._init_) );
185
+ if( !(index<0) )
186
+ db[_params.db][_params.table].splice( index,1,body );
152
187
 
153
- return {
188
+ save( _params ); return [{
154
189
  database: _params.db,
155
- status: 'DB added'
156
- };
157
-
190
+ table: _params.table,
191
+ status: 'udated'
192
+ }];
158
193
  }
159
194
 
160
- function removeDB( _params ){
195
+ async function remove( _params ){
161
196
 
162
- const init = `${query.path}/_init_.json`;
163
- const i = db._init_.DB.findIndex(x=>{
164
- return x.name == _params.db
165
- });
197
+ const index = db[_params.db][_params.table].findIndex(x=>{
198
+ const regex = new RegExp(_params.target,'gi');
199
+ return regex.test(x);
200
+ });
166
201
 
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);
202
+ if( !(index<0) )
203
+ db[_params.db][_params.table].splice( index,1 );
171
204
 
172
- db[_params.db] = new Array();
173
- fs.writeFileSync( init,JSON.stringify(db._init_) );
205
+ save( _params ); return [{
206
+ database: _params.db,
207
+ table: _params.table,
208
+ status: 'removed'
209
+ }];
210
+ }
174
211
 
175
- return {
212
+ async function save( _params ){
213
+
214
+ modifyDB( _params.db,_params.table );
215
+ return [{
176
216
  database: _params.db,
177
217
  table: _params.table,
178
- status: 'DB deleted'
179
- };
218
+ status: 'saved'
219
+ }];
220
+ }
221
+
222
+ /* --------------------------------------------------------------------------------------- */
223
+
224
+ function addDB( _params ){
225
+ try{
226
+
227
+ const init = `${query.path}/_init_.json`;
228
+
229
+ db._init_.DB.push({
230
+ name: _params.db,
231
+ tables: []
232
+ });
233
+
234
+ db[_params.db] = new Array();
235
+ fs.writeFileSync( init,JSON.stringify(db._init_) );
180
236
 
237
+ return [{
238
+ database: _params.db,
239
+ status: 'DB added'
240
+ }];
241
+
242
+ } catch(e) { }
181
243
  }
182
244
 
183
- function modifyDB( _name, _table ){
245
+ function removeDB( _params ){
246
+ try{
184
247
 
185
- const init = `${query.path}/_init_.json`;
186
- const path = `${query.path}/${_table}.json`;
248
+ const init = `${query.path}/_init_.json`;
249
+ const i = db._init_.DB.findIndex(x=>{
250
+ return x.name == _params.db
251
+ });
252
+
253
+ db._init_.DB[i].tables.forEach(x=>{
254
+ const path = `${query.path}/${x}.json`;
255
+ fs.unlinkSync(path);
256
+ }); db._init_.DB.splice(i,1);
257
+
258
+ db[_params.db] = new Array();
259
+ fs.writeFileSync( init,JSON.stringify(db._init_) );
260
+
261
+ return [{
262
+ database: _params.db,
263
+ table: _params.table,
264
+ status: 'DB deleted'
265
+ }];
187
266
 
188
- fs.writeFileSync( init,JSON.stringify(db._init_) );
267
+ } catch(e) { }
268
+ }
189
269
 
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
- }
270
+ function modifyDB( _name, _table ){
271
+ try{
197
272
 
273
+ const init = `${query.path}/_init_.json`;
274
+ const path = `${query.path}/${_table}.json`;
275
+
276
+ fs.writeFileSync( init,JSON.stringify(db._init_) );
277
+
278
+ try {
279
+ const length = db[_name][_table].length;
280
+ if( length>0 ) encryptDB( _name, _table, path );
281
+ else fs.writeFileSync( path,'' );
282
+ } catch(e) {
283
+ fs.unlinkSync( path );
284
+ }
285
+
286
+ } catch(e) { }
198
287
  }
199
288
 
200
289
  /* --------------------------------------------------------------------------------------- */
@@ -213,13 +302,12 @@ function addTable( _params ){
213
302
  }); db._init_.DB[i].tables.push(_params.table);
214
303
 
215
304
  db[_params.db][_params.table] = new Array();
216
- modifyDB( _params.db,_params.table );
217
305
 
218
- return {
306
+ return [{
219
307
  database: _params.db,
220
308
  table: _params.table,
221
309
  status: 'table added'
222
- };
310
+ }];
223
311
 
224
312
  }
225
313
 
@@ -235,28 +323,42 @@ function removeTable( _params ){
235
323
 
236
324
  db._init_.DB[i].tables.splice(j,1);
237
325
  delete db[_params.db][_params.table];
238
- modifyDB( _params.db,_params.table );
239
326
 
240
- return {
327
+ return [{
241
328
  database: _params.db,
242
329
  table: _params.table,
243
330
  status: 'table removed'
244
- };
331
+ }];
245
332
 
246
333
  }
247
334
 
248
335
  /* --------------------------------------------------------------------------------------- */
249
336
 
250
- (async()=>{
251
- try{
337
+ function refresh( _params ){
338
+ return new Promise((response,reject)=>{
339
+ _init_().then(()=>{ response([{status: 'done'}]) })
340
+ .catch((e)=>{ reject([{status:'error',message:e.message}]) });
341
+ });
342
+ }
252
343
 
253
- const api = url.parse( req.url,true );
254
- const params = api.query;
344
+ /* --------------------------------------------------------------------------------------- */
345
+
346
+ (async ()=>{
347
+ try{
348
+
349
+ body = await getBody();
350
+ params = await validate(params);
255
351
 
256
352
  /* Find Api */
257
353
  if( api.pathname == '/list' ) json( await list(params) )
258
354
  else if( api.pathname == '/hash' ) json( await hash(params) )
259
355
  else if( api.pathname == '/match' ) json( await match(params) )
356
+ else if( api.pathname == '/update' ) json( await update(params) )
357
+
358
+ /* Save Api */
359
+ else if( api.pathname == '/save' ) json( await save(params) )
360
+ else if( api.pathname == '/remove' ) json( await remove(params) )
361
+ else if( api.pathname == '/refresh' ) json( await refresh(params) )
260
362
 
261
363
  /* Remove Api */
262
364
  else if( api.pathname == '/pop' ) json( await pop(params) )
@@ -277,7 +379,7 @@ function removeTable( _params ){
277
379
 
278
380
  else error('Oops something went wrong');
279
381
 
280
- } catch(e) { error(e); }
382
+ } catch(e) { error(e?.message||e); }
281
383
  })();
282
384
 
283
385
  /* --------------------------------------------------------------------------------------- */
@@ -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.6",
4
+ "version": "1.0.10",
5
5
  "name": "molly-db",
6
6
  "author": "bececrazy",
7
7
  "scripts": {