-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcrud.js
1275 lines (1092 loc) · 51.2 KB
/
crud.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// CRUD Create Read Update Delete Interface
// (c)copyright 2014 by Gerald Wodni <[email protected]>
"use strict";
var _ = require("underscore");
var async = require("async");
var bcrypt = require("bcrypt-nodejs");
var moment = require("moment");
var fs = require("fs");
var mkdirp = require("mkdirp");
var fsPath = require("path");
var express = require("express");
module.exports = function _crud( k ) {
/* TODO: sql CRUD */
function sqlCrud( db, opts ) {
opts = opts || {};
opts = _.extend( {
key: "id",
foreignName: "name",
foreignNameSeparator: " ",
orderBy: opts.foreignName || "name",
selectFields: "",
nestTables: false
}, opts );
opts = _.extend( {
idField: opts.id,
insertQuery: "INSERT INTO ?? SET ?",
updateQuery: "UPDATE ?? SET ? WHERE ??=?",
deleteQuery: "DELETE FROM ?? WHERE ??=?",
selectAllQuery: { sql: "SELECT * " + opts.selectFields + " FROM ?? ORDER BY ??", nestTables: opts.nestTables },
selectIdQuery: { sql: "SELECT * " + opts.selectFields + " FROM ?? WHERE ??=?", nestTables: opts.nestTables },
selectForeignKeyQuery: "SELECT ??, ?? FROM ?? ORDER BY ??"
}, opts );
opts = _.extend( {
selectListQuery: opts.selectAllQuery
}, opts );
function create( obj, callback ) {
/* remove primary key if transmitted */
if( opts.autoKey && _.has( obj, opts.key ) )
delete obj[ opts.key ];
db.query( opts.insertQuery, [ opts.table, obj ], callback );
}
function createOrUpdate( obj, callback ) {
var key = obj[ opts.key ];
read( key, function( err, data ) {
if( err )
return callback( err, [] );
if( data.length == 0 )
create( obj, callback );
else
update( key, obj, callback );
});
}
function read( key, callback ) {
var values = [ opts.table, opts.key, key ];
if( _.has( key, "key" ) ) {
values = key;
values.values = [ opts.table, opts.key, key.key ];
}
db.query( opts.selectIdQuery, values, function( err, data ) {
if( err )
callback( err );
else if( data.length == 0 )
callback( null, [] );
else
callback( null, data[0], data );
});
}
function readAll( callback ) {
db.query( opts.selectAllQuery, [ opts.table, opts.orderBy ], callback );
}
function countItems( callback ) {
db.query( "SELECT COUNT(*) AS count FROM ??", [ opts.table ], callback );
}
function pagePrefixes( callback, prefixLength ) {
db.query( "SELECT UPPER(LEFT(??, ?)) AS letter FROM ?? GROUP BY letter", [ opts.orderBy, prefixLength, opts.table ], (err, items) => {
if( err ) return callback( err );
const prefixes = items.map( row => row.letter );
console.log( "PREFIXES:".bold.red, prefixes );
callback( null, prefixes );
});
}
/* TODO: difference to readForeignKey? function really needed to justify enum foreignBoldName? */
function readList( callback, listOpts ) {
listOpts = listOpts || {};
db.query( listOpts.query || opts.selectListQuery, listOpts.parameters || [ opts.table, opts.orderBy ], callback );
}
function pReadDisplayList( lastSync, listOpts = {} ) {
return new Promise( (fulfill, reject) => {
readDisplayList( lastSync, (err, data) => {
if( err )
return reject( err );
fulfill( data );
}, listOpts );
});
}
function readDisplayList( lastSync, callback, listOpts ) {
listOpts = listOpts || {};
var query = listOpts.query || opts.selectListQuery;
var sql = "SELECT REPLACE(NOW(), ' ', '_') AS now; ";
const untilParam = listOpts.until ? "?" : "NOW()";
if( listOpts.useDeleteLog )
sql+= "SELECT moduleUin FROM deleteLog WHERE module=? AND `deleted` BETWEEN ? AND " + untilParam + "; ";
else
sql+= "SELECT ?? FROM ?? ORDER BY ??; ";
sql+= (query.sql || query).replace( /ORDER BY/, 'WHERE ??.modified BETWEEN ? AND ' + untilParam + ' ORDER BY' );
const parameters = listOpts.parameters || [
( listOpts.useDeleteLog ? [ opts.table, lastSync ] : [ opts.key, opts.table, opts.key ] ), /* ids */
( listOpts.useDeleteLog && listOpts.until ? [ listOpts.until ] : [] ), /* until */
[ opts.table, opts.table, lastSync ], /* query */
( listOpts.until ? [ listOpts.until ] : [] ),
[ opts.orderBy ], /* order */
].flat();
if( listOpts.hasOwnProperty("page") && listOpts.pageSize ) {
sql += "LIMIT ?, ?";
parameters.push( listOpts.page * listOpts.pageSize ); // offset
parameters.push( listOpts.pageSize ); // row count
}
db.query( { sql: sql, nestTables: query.nestTables || false }, parameters, function( err, data ) {
if( err ) return callback( err );
var displayRows = [];
data[2].forEach( row => {
var displayRow = {
id: k.rdb.getField( row, opts.key ),
prefixes: {}
};
var extraFields = opts.displayExtraFields || [];
var prefixes = opts.displayPrefixes || [];
/* base info */
if( opts.foreignName )
displayRow.display = k.rdb.getField( row, opts.foreignName );
if( opts.foreignBoldName && prefixes.length == 0 )
displayRow.boldDisplay = k.rdb.getField( row, opts.foreignBoldName );
/* fields */
extraFields.forEach( field => {
displayRow[ field ] = k.rdb.getField( row, field );
});
/* prefixes */
prefixes.forEach( displayPrefix => {
displayRow.prefixes[ displayPrefix.id ] = k.rdb.getField( row, displayPrefix.id );
displayRow.prefixes[ displayPrefix.name ] = k.rdb.getField( row, displayPrefix.name );
});
displayRows.push( displayRow );
});
/* delete ids */
var deleteIds = [];
var lastId = 1;
if( listOpts.useDeleteLog )
deleteIds = [... data[1] ].map( r => r.moduleUin );
else
data[1].forEach( row => {
while( lastId++ < row.uin )
deleteIds.push( lastId - 1 );
});
callback( null, {
now: data[0][0].now,
//ids: _.map( data[1], row => row.uin ),
deleteIds: deleteIds,
displayRows: displayRows
});
});
}
function readForeignKey( callback, foreignOpts ) {
readList( function( err, data ) {
if( err )
return callback( err );
var items = _.map( data, function( row ) {
var name = k.rdb.getField( row, opts.foreignName );
if( opts.foreignBoldName )
name = k.rdb.getField( row, opts.foreignBoldName ) + opts.foreignNameSeparator + name;
return {
id: k.rdb.getField( row, opts.key ),
name: name
}
});
callback( err, items );
}, foreignOpts );
}
function readWhere( name, values, callback ) {
var where = Object.assign({
fields: "*",
joins: "",
}, opts.wheres[ name ]);
values.unshift( opts.table ); /* make table the first item */
values.push( opts.orderBy ); /* add order by */
db.query( `SELECT ${where.fields} FROM ?? ${where.joins} WHERE ${where.where} ORDER BY ??`, values, callback );
}
function update( key, obj, callback ) {
if( opts.disallowKeyUpdate )
delete obj[opts.key];
db.query( opts.updateQuery, [ opts.table, obj, opts.key, key ], callback );
}
function del( key, callback ) {
db.query( opts.deleteQuery, [ opts.table, opts.key, key ], callback );
}
return _.extend(
{
create: create,
createOrUpdate: createOrUpdate,
read: read,
readAll:readAll,
countItems: countItems,
pagePrefixes,
readList: readList,
readDisplayList: readDisplayList,
pReadDisplayList,
readForeignKey: readForeignKey,
readWhere: readWhere,
update: update,
del: del,
foreignKeys: opts.foreignKeys || [],
type: "sql"
}, opts );
}
function setHash( module, opts ) {
opts = opts || {};
/* default key construction */
var separator = opts.separator || ":";
function getIndexKey( prefix ) {
return prefix + separator + module;
};
function getKeyBase( prefix ) {
return prefix + separator + module + separator;
};
function getKey( prefix, id ) {
return getKeyBase( prefix ) + id;
};
opts = _.extend( {
getIndexKey: getIndexKey,
getKeyBase: getKeyBase,
getKey: getKey
}, opts);
/* crud */
function create( prefix, id, obj, callback ) {
if( typeof callback != "function" )
throw new Error( "crud.create: invalid callback provided" );
async.series( [
function( done ) { k.rdb.sadd( opts.getIndexKey( prefix ), id, done ); },
function( done ) { k.rdb.hmset( opts.getKey( prefix, id ), obj, done ); }
], callback );
};
function readAll( prefix, callback) {
k.rdb.shgetall( opts.getIndexKey( prefix ), opts.getKeyBase( prefix ), callback );
};
function read( prefix, id, callback ){
k.rdb.hgetall( opts.getKey( prefix, id ), callback );
};
function del( prefix, id, callback ) {
async.parallel( [
function( done ) { k.rdb.srem( opts.getIndexKey( prefix ), id, done ); },
function( done ) { k.rdb.del( opts.getKey( prefix, id ), done ); },
], callback );
};
function update( prefix, id, obj, callback ) {
updateId( prefix, id, id, obj, callback );
}
function updateId( prefix, oldId, newId, obj, callback ) {
async.series( [
function( d ) { del( prefix, oldId, d ); },
function( d ) { create( prefix, newId, obj, d ); }
], callback );
}
return {
create: create,
read: read,
readAll: readAll,
update: update,
updateId: updateId,
del: del
}
}
function setSet( module, opts ) {
opts = opts || {};
/* default key construction */
var separator = opts.separator || ":";
function getIndexKey( prefix ) {
return prefix + separator + module;
};
function getKeyBase( prefix ) {
return prefix + separator + module + separator;
};
function getKey( prefix, id ) {
return getKeyBase( prefix ) + id;
};
opts = _.extend( {
getIndexKey: getIndexKey,
getKeyBase: getKeyBase,
getKey: getKey
}, opts);
/* crud */
function create( prefix, id, obj, callback ) {
if( typeof callback != "function" )
throw new Error( "crud.create: invalid callback provided" );
async.series( [
function( done ) { k.rdb.sadd( opts.getIndexKey( prefix ), id, done ); },
function( done ) { k.rdb.sadd( opts.getKey( prefix, id ), obj, done ); }
], callback );
};
function readAll( prefix, callback) {
k.rdb.ssgetall( opts.getIndexKey( prefix ), opts.getKeyBase( prefix ), callback );
};
function read( prefix, id, callback ){
k.rdb.smembers( opts.getKey( prefix, id ), callback );
};
function del( prefix, id, callback ) {
async.parallel( [
function( done ) { k.rdb.srem( getIndexKey( prefix ), id, done ); },
function( done ) { k.rdb.srem( getKey( prefix, id ), done ); },
], callback );
};
function update( prefix, oldId, newId, obj, callback ) {
async.series( [
function( d ) { del( prefix, oldId, d ); },
function( d ) { create( prefix, newId, obj, d ); }
], callback );
}
return {
create: create,
read: read,
readAll:readAll,
update: update,
del: del
}
}
/* extends base crud (create, read, readAll, update, del) to full crud */
function base( crud ) {
if( !_.has( crud, "readList" ) )
crud.readList = function _baseCrud_readList( callback ) {
crud.readAll( callback );
};
if( !_.has( crud, "readForeignKey" ) )
crud.readForeignKey = function _baseCrud_readList( callback ) {
crud.readAll( callback );
};
/* already set in sqlCrud, but missing rdb cruds like users */
_.defaults( crud, {
foreignName: "name",
foreignNameSeparator: " "
});
return crud;
}
/* make website-based crud website unaware */
function unPrefix( crud ) {
//var unCrud = {
// create, update, del( key )
// copy all non-functions?
// clone all?
//}
/* references to original crud */
//var create = crud.create;
//var read = crud.read;
//var readAll = crud.readAll;
//var update = crud.update;
//var del = crud.del;
var unCrud = _.clone( crud );
return function _unPrefixCrud( req ){
var website = req.kern.website;
/* wrap methods and supply website */
/* fixthis: extend overrides original crud, return copy instead! */
return _.extend( unCrud, {
create: function _unPrefixCrud_create( obj, callback ) {
crud.create( website, obj, callback );
},
read: function _unPrefixCrud_read( key, callback ) {
crud.read( website, key, callback );
},
readAll:function _unPrefixCrud_readAll( callback ) {
crud.readAll( website, callback );
},
update: function _unPrefixCrud_update( key, obj, callback ) {
crud.update( website, key, obj, callback );
},
del: function _unPrefixCrud_del( key, callback ) {
crud.del( website, key, callback );
}
} );
//return _.extend( crud, {
// create: function _unPrefixCrud_create() {
// create.apply( crud, [ req.kern.website ].concat( Array.prototype.slice.call(arguments) ) );
// },
// read: function _unPrefixCrud_read() {
// read.apply( crud, [ req.kern.website ].concat( Array.prototype.slice.call(arguments) ) );
// },
// readAll:function _unPrefixCrud_readAll() {
// readAll.apply( crud, [ req.kern.website ].concat( Array.prototype.slice.call(arguments) ) );
// },
// update: function _unPrefixCrud_update() {
// update.apply( crud, [ req.kern.website ].concat( Array.prototype.slice.call(arguments) ) );
// },
// del: function _unPrefixCrud_del() {
// del.apply( crud, [ req.kern.website ].concat( Array.prototype.slice.call(arguments) ) );
// }
//});
};
};
/* wrapper to unPrefix and base a crud, allows to use crud by just calling it with reg as argument */
function unPrefixBase( crud ) {
var unprefixedCrud = unPrefix( crud );
return function _unPrefixBase( req ) {
return base( unprefixedCrud( req ) );
}
}
function fieldManager( opts ) {
opts = _.extend( {
id: "id",
idField: opts.id || "id",
filters: {
date: "dateTime",
email: "email",
number: "decimal",
enum: "id",
tel: "telephone",
text: "text",
foreign: "uint",
textarea: "text",
checkbox: "exists",
password: "passwords",
folder: "filepath",
file: "filepath",
upload: "drop",
image: "filepath",
hiddenId: "id",
h3: "drop",
h4: "drop",
p: "drop"
},
elements: {
date: "date-field",
email: "email-field",
enum: "enum-field",
foreign: "foreign-field",
number: "number-field",
tel: "tel-field",
text: "text-field",
textarea: "textarea-field",
checkbox: "checkbox-field",
password: "password-field",
folder: "enum-field",
file: "enum-field",
upload: "file-field",
image: "enum-field",
hiddenId: "hidden-field",
h3: "h3",
h4: "h4",
p: "p"
},
fields: {
id: { type: "id" },
name: { type: "alnum" },
value: { type: "allocnum" }
},
success: function( req, res, next ) {
req.method = "GET";
next();
},
__error: function( err, req, res, next ) {
req.method = "GET";
req.messages.push( { type: "danger", title: req.locales.__("Error"), text: req.locales.__( err ) } );
next();
},
error: function( err, req, res, next ) {
req.method = "GET";
req.messages.push( { type: "danger", title: req.locales.__("Error"), text: err } );
next();
}
}, opts );
opts = _.extend( {
readFields: function( req ) {
var values = {};
var fields = _.isFunction( opts.fields ) ? opts.fields( req ) : opts.fields;
_.each( fields, function( fieldOpts, field ) {
var source = fieldOpts.source || "postman";
var filterName = fieldOpts.filter || opts.filters[ fieldOpts.type ] || field;
if( !_.has( k.filters, filterName ) && filterName != 'exists' && filterName != 'get' && filterName != 'drop' && filterName != 'passwords' )
throw new Error( "CRUD: Undefined Filter >" + filterName + "< (field:" + field + ")" );
//console.log( "FILTER:", source, filterName, field );
/* drop value */
if( filterName == 'drop' )
return;
/* get value without applying any filter (for sources which do not support filters) */
else if( filterName == 'get' )
values[ field ] = req[ source ][ fieldOpts.name || field ];
/* fetch value using filters */
else if( filterName == 'passwords' ) {
var password = req[source].password( field );
if( password && password.length > 0 )
{
if( !req.postman.fieldsMatch( field, field + "2" ) )
throw req.locales.__( "Passwords do not match" );
if( password.length < k.users.minPasswordLength )
throw req.locales.__( "Password too short, minimum: {0}" ).format( k.users.minPasswordLength );
values[ field + "Hash" ] = bcrypt.hashSync( password );
}
}
else
try {
values[ field ] = req[ source ][ filterName ]( fieldOpts.name || field );
}
catch( err ) {
/* attempt to resolve error to human readabletext */
if( typeof req[ source ] === "undefined" )
throw new Error( "readFields: unknown source '" + source + "'" );
if( typeof req[ source ][ filterName ] === "undefined" )
throw new Error( "readFields: unknown filtername '" + filtername + "' from source '" + source + "'" );
throw err;
}
/* local date format to iso */
if( fieldOpts.type == "date" )
values[ field ] = moment( values[ field ], req.locales.__( "date-format-moment" ) ).format("YYYY-MM-DD HH:mm:ss");
});
return values;
},
getRequestId: function( req ) {
return req.requestman.escapedLink( opts.idField );
}
}, opts );
return opts;
}
function crudManager( crud, opts ) {
opts = fieldManager( opts );
if( opts.unPrefix ) {
opts = _.extend( opts, { unPrefixedCrud: unPrefixBase( crud ) } );
opts = _.extend( opts, { getCrud: function _getCrudUnPrefixed( req ) {
return opts.unPrefixedCrud( req );
} });
}
else
if( crud.type === "sql" )
opts = _.extend( opts, { getCrud: function _getCrudSql( req ) {
/* overwrite sql-crud for this very call (bind req) */
return _.extend( {}, crud, {
read: function _crudManager_sql_read( key, callback ) {
crud.read( { req: req, key: key }, callback );
}
});
} });
else
opts = _.extend( opts, { getCrud: function _getCrudPlain() {
return crud;
} });
return opts;
}
/* edit, TODO: remove crud.length ifs */
function router( k, path, crud, opts ) {
opts = crudManager( crud, opts );
opts = _.extend( {
preCreateTrigger: function( req, fields, crudCreate ) {
crudCreate( fields );
}
}, opts );
function handlePost( req, res, next ) {
var postOpts = {};
var files = [];
if( opts.fileUpload ) {
postOpts.onFile = function( fieldname, file, filename, encoding, mimetype ) {
if( !opts.fields[fieldname] || opts.fields[fieldname].type !== "upload" ) {
req.messages.push( { type: "danger", title: req.locales.__("Error"), text: "Non-upload-field file-upload" } );
console.log( "Non-upload-field file-upload:".bold.red, fieldname );
return file.resume();
}
var f = {
fieldname: fieldname,
originalFilename: filename,
filename: k.filters.filename( filename.replace( /\s+/g, "_" ) ),
encoding: encoding,
mimetype: mimetype,
content: Buffer.alloc(0),
complete: false
};
files.push( f );
file.on("data", (chunk) => f.content = Buffer.concat([ f.content, chunk ]) );
file.on("end", () => f.complete = true );
}
}
function storeFiles( store ) {
if( store.length == 0 )
return opts.success( req, res, next );
var obj = {};
async.each( store, (file, done) => {
/* ignore empty uploads */
if( file.content.length == 0 )
return done();
/* update-obj */
obj[ file.name ] = file.value;
/* save file */
mkdirp( fsPath.dirname( file.filename ), (err) => {
if( err ) return done( err );
fs.writeFile( file.filename, file.content, done );
});
}, (err) => {
if( err )
return opts.__error( err, req, res, next );
/* update crud's file pointer */
if( _.keys(obj).length == 0 )
return opts.success( req, res, next );
opts.getCrud( req ).update( req.kern.crudId, obj, (err) => {
if( err )
return opts.__error( err, req, res, next );
opts.success( req, res, next );
});
});
}
k.postman( req, res, postOpts, function() {
try {
if( req.postman.exists( "add" ) || req.postman.exists( "addRetain" ) ) {
var obj = opts.readFields( req );
if( req.postman.exists( "addRetain" ) )
req.retainValues = obj;
var handleCreate = function _handleCreate( err, data ) {
if( err )
return opts.__error( err, req, res, next );
var insertId = ( data || {} ).insertId;
req.kern.crudId = insertId;
req.messages.push( { type: "success", title: req.locales.__("Success"), text: req.locales.__("Item added"),
attributes: { "data-insert-id": insertId }
} );
/* on successfull insert: handle files */
if( opts.fileUpload )
opts.fileUpload( req, res, next, files, storeFiles )
else if( opts.redirectAddToEdit )
return res.redirect( fsPath.join( opts.path, "edit", req.kern.crudId.toString() ) );
else
opts.success( req, res, next );
};
opts.preCreateTrigger( req, obj, function( obj ) {
opts.getCrud(req).create( obj, handleCreate );
});
}
else if( req.postman.exists( "update" ) ) {
var id = opts.getRequestId( req );
var obj = opts.readFields( req );
req.kern.crudId = id;
var handleUpdate = function _handleUpdate( err ) {
if( err )
return opts.__error( err, req, res, next );
req.messages.push( { type: "success", title: req.locales.__("Success"), text: req.locales.__("Item updated") } );
/* on successfull update: handle files */
if( opts.fileUpload )
opts.fileUpload( req, res, next, files, storeFiles )
else
opts.success( req, res, next );
};
opts.getCrud(req).update( id, obj, handleUpdate );
}
else if( req.postman.exists( "delete" ) ) {
var id = req.postman.escapedLink( "delete" );
var handleDelete = function _handleDelete( err ) {
if( err )
return opts.__error( err, req, res, next );
req.messages.push( { type: "success", title: req.locales.__("Success"), text: req.locales.__("Item deleted") } );
opts.success( req, res, next );
};
opts.getCrud(req).del( id, handleDelete );
}
else {
next();
}
}
catch(e) {
if( e.toString().indexOf( "Error:" ) == -1 )
opts.error( e, req, res, next );
else
throw e;
}
});
};
/* set post routes */
if( path instanceof Array )
path.forEach( function( p ) {
k.router.post( p, handlePost );
});
else
k.router.post( path, handlePost );
return {
handlePost: handlePost,
getRequestId: opts.getRequestId,
getFields: function( req ) {
var jadeFields = {};
var fields = _.isFunction( opts.fields ) ? opts.fields( req ) : opts.fields;
_.each( fields, function( fieldOpts, field ) {
/* ignore fields with no type (idsignore fields with no type (ids)) */
if( fieldOpts.type ) {
var element = "text-field"
if( _.has( opts.elements, fieldOpts.type ) )
element = opts.elements[ fieldOpts.type];
else if( opts.customElements instanceof Array && opts.customElements.indexOf( fieldOpts.type ) >= 0 )
element = fieldOpts.type;
else
throw new Error( "CRUD Unknown Element " + fieldOpts.type );
//console.error( "CRUD Element ".magenta.bold, element, "(" + field + ": " + fieldOpts.type + ")" );
/** some fields require special **/
/* translate values */
if( _.has( fieldOpts, "keys" ) && ( !_.has( fieldOpts, "keyValues" ) || fieldOpts.retranslate ) ) {
fieldOpts.keyValues = {}
fieldOpts.retranslate = true; // retranslate: force recompute on keyValues, otherwise first translation persists
_.each( fieldOpts.keys, function( key ) {
fieldOpts.keyValues[ key ] = req.locales.__( key );
});
}
jadeFields[ field ] = _.extend( fieldOpts, {
mixinType: element
});
}
} );
return jadeFields;
},
getValues: function( req, fields, values ) {
_.each( values, function( value, key ) {
if( !_.has( fields, key ) )
return;
if( fields[ key ].mixinType == "date-field" ) {
var t = moment( values[ key ] );
if( t.isValid() )
values[ key ] = t.format( req.locales.__( "date-format-moment" ) );
else
values[ key ] = "";
}
});
return values;
},
crud: crud,
getCrud: opts.getCrud
};
};
/* linker: expose for AJAX */
function linker( k, crud, opts ) {
opts = crudManager( crud, opts );
opts = _.extend( {
id: "id",
path: "/"
}, opts);
opts = _.extend( {
readPath: fsPath.join( opts.path, "read/:id?" ),
idField: "id",
readAllPath: fsPath.join( opts.path, "read-all" ),
readListPath: fsPath.join( opts.path, "read-list" ),
readDisplayListPath: fsPath.join( opts.path, "read-display-list/:lastSync" ),
createPath: fsPath.join( opts.path, "create" ),
updatePath: fsPath.join( opts.path, "update/:id?" ),
deletePath: fsPath.join( opts.path, "delete/:id?" )
}, opts);
//var r = router( k, [ opts.createPath, opts.readPath, opts.updatePath, opts.deletePath ], crud, opts );
//var r = express.Router();
var r = k.router;
function applyPostman( callback ) {
return function( req, res, next ) {
k.postman( req, res, function() {
callback( req, res, next );
});
};
};
r.get( opts.readPath, function( req, res, next ) {
opts.getCrud(req).read( req.requestman.escapedLink( opts.idField ), function( err, data ) {
if( err ) next( err ); else res.json( data );
});
});
r.get( opts.readListPath, function( req, res, next ) {
opts.getCrud(req).readList( function( err, data ) {
if( err ) next( err ); else res.json( data );
});
});
r.get( opts.readDisplayListPath, function( req, res, next ) {
opts.getCrud(req).readDisplayList( req.requestman.dateTime( "lastSync" ), function( err, data ) {
if( err ) next( err ); else res.json( data );
});
});
r.get( opts.readAllPath, function( req, res, next ) {
opts.getCrud(req).readAll( function( err, data ) {
if( err ) next( err ); else res.json( data );
});
});
/* wheres, currently only supported for sql, if needed can be extended by handling readWhere in unPrefixedCrud */
_.each( crud.wheres, function( where, name ) {
var url = fsPath.join( opts.path, "where", name );
where.parameters.forEach( function( parameter ) {
url = fsPath.join( url, ":" + parameter.name );
});
r.get( url, function( req, res, next ) {
var values = [];
where.parameters.forEach( function( parameter ) {
values.push( req.requestman[ parameter.filter || "alnum" ]( parameter.name ) );
});
crud.readWhere( name, values, function( err, data ) {
if( err )
return next( err );
res.json( data );
});
});
});
if( !opts.readOnly ) {
r.post( opts.createPath, applyPostman( function( req, res, next ) {
opts.getCrud(req).create( opts.readFields( req ), function( err, data ) {
if( err ) next( err ); else res.json( { insertId: data.insertId } );
});
}) );
r.post( opts.updatePath, applyPostman( function( req, res, next ) {
var id = req.requestman.escapedLink( opts.idField );
var data = opts.readFields( req );
if( !id )
id = data[ opts.id ];
opts.getCrud(req).update( id, data, function( err ) {
if( err ) next( err ); else res.json( {} );
});
}) );
var deleteHandler = function _deleteHandler( req, res, next ) {
var id = req.requestman.escapedLink( opts.idField );
if( req.method != "GET" ) {
var data = opts.readFields( req );
if( !id )
id = data[ opts.id ];
}
opts.getCrud(req).del( id, function( err ) {
if( err ) next( err ); else res.json( {} );
});
}
r.get ( opts.deletePath, deleteHandler );
r.post( opts.deletePath, applyPostman( deleteHandler ) );
}
};
function getOptional( k, optional, req ) {
if( _.isBoolean( optional ) )
return optional;
if( _.has( optional, "permission" ) )
return k.reg("admin").allowed( req, optional.permission );
throw new Error( "CRUD unknown optional: " + optional.toString() );
}
function presenter( k, crud, opts ) {
opts = _.extend( {
id: "id",
addPath: "/",
title: "Crud",
path: "/admin/crud",
idField: "id",
editPath: "/edit/:id?",
jadeFile: "admin/crud",
showAdd: true,
showList: true
}, opts);
var r = router( k, [ opts.addPath, opts.editPath ], crud, opts );
function renderAll( req, res, next, values, fullData, renderOpts ) {
k.getman( req );
renderOpts = renderOpts || {};
var renderCrud = r.getCrud( req );
var hiddenForeignKeyData = {};
var listOpts = {};
if( opts.selectEditListQuery && _.isObject( values ) ) {
listOpts.query = opts.selectEditListQuery;
listOpts.parameters = values;
}
var currentPage = 0;
var currentPrefix = 'A';
var pageCount = 0;
var pagePrefixes = [];
var showMode = 'all';