forked from adamspe/odata-resource
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
831 lines (829 loc) · 31.9 KB
/
index.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
var debug = require('debug')('Resource'),
express = require('express'),
filterParser = require('./odata-filter'),
querystring = require('querystring');
/**
* <p>Constructs a resource.</p>
*
* <p>Keys</p>
*
* <ul>
* <li>model (object): The instance of the Mongoose model (required).</li>
* <li>rel (string): The absolute path of the new resource (required).</li>
* <li>create (boolean): Specifies if the resource should support create (POST) (default true).</li>
* <li>update (boolean): Specifies if the resource should support update (PUT) (default true).</li>
* <li>delete (boolean): Specifies if the resource should support delete (DELETE) (default true).</li>
* <li>lean (boolean): Whether find[ById] queries should be 'lean' and return pojos (default true). If false then
* resource instances, prior to mapping an object for return, could make use of methods on the instance model.</li>
* <li>populate (string||Array): Specifies a property, or list of properties, to populate into objects (<strong>deprecated</strong> use <code>$expand</code>).</li>
* <li>count (boolean): Specifies if the resource should support counts on find and when traversed to by standard relationships from other types (default: false).</li>
* </ul>
*
* <p>The following keys set defaults for possible query arguments.</p>
* <ul>
* <li>$top (number): The default value for $top if not supplied on the query string (default none).</li>
* <li>$skip (number): The default value for $skip if not supplied on the query string (default none).</li>
* <li>$orderby (string): The default value for $orderby if not supplied on the query string (default none). This value
* must use odata syntax like "foo asc,bar desc,baz" rather than mongo syntax like "foo -bar baz".</li>
* <li>$orderbyPaged (string): The name of an attribute to sort results by when clients are paging, send $top, but have not
* explicitly sent $orderby. (default '_id').</li>
* <li>$select (string): The default value for $select if not supplied on the query string (default none, all properties).
* If a value is supplied then $select on the query string will be ignored to protect against the
* situation where the intent is to hide internal attributes (e.g. '-secret'). Unlike odata the
* syntax here is passed through to mongo so the '-' prefix will be honored.</li>
* <li>$expand (string|Array): Specifies a property or list of properties to populate into objects. This value acts as the
* default value for the <code>$expand</code> URL argument. If the URL argument is supplied it
* over-rides this value. Nested expansion is supported. E.g. <code>_book._author</code> will end up in
* both the <code>_book</code> reference being expanded and its <code>_author</code> reference being expanded.
* The corresponding Mongoose model <code>ObjectId</code> properties <strong>must</strong> have their
* <code>ref</code> properties set properly or expansion cannot work.</li>
* </ul>
*
* @constructor
* @param {Object} definition The resource definition.
*/
var Resource = function(definition) {
var self = this;
this._definition = Object.assign({count: false},definition);
// console.log(this._definition)
if(this._definition.count) {
this._definition.staticLinks = {
'count': function(req,res) { self.count(req,res); }
}
}
};
/**
* Send a response error.
* @todo currently this function unconditionally sends the error with the response.
* this may not be desirable since often exposing an error (e.g. stack trace) poses
* a potential security vulnerability.
*
* @param {Object} res The express response object.
* @param {Number} rc The response status code (default 500).
* @param {String} message The response message.
* @param {Object} err The error object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the error object.
*/
Resource.sendError = function(res,rc,message,err,next) {
rc = rc||500;
var response = {
status: rc,
message: message,
err: err
};
res.status(rc).send(response);
if(typeof(next) === 'function') {
next(err||response);
}
};
/**
* Parse a $filter populating a mongoose query with its cotents.
*
* @param {Object} A mongoose query.
* @param {String} A $filter value.
*/
Resource.parseFilter = filterParser;
/**
* @return {Object} The resource definition.
*/
Resource.prototype.getDefinition = function() {
return this._definition;
};
/**
* @return {String} The odata service name.
*/
Resource.prototype.getOName = function() {
return this._definition.oname;
};
/**
* @return {String} The odata service type.
*/
Resource.prototype.getOType = function() {
return this._definition.otype;
};
/**
* @return {Object} The odata url key.
*/
Resource.prototype.getOKey = function() {
return this._definition.okey;
};
/**
* @return {String} The service is a leaf node.
*/
Resource.prototype.getLeaf = function() {
return this._definition.leaf;
};
/**
* @return {Object} The rest of the content.
*/
Resource.prototype.getContent = function() {
return this._definition.content;
};
/**
* @return {String} The resource relative path.
*/
Resource.prototype.getRel = function() {
return this._definition.rel;
};
/**
* @return {Object} The underlying mongoose model.
*/
Resource.prototype.getModel = function() {
return this._definition.model;
};
/**
* @return {Array} The list of instance link names.
*/
Resource.prototype.getInstanceLinkNames = function() {
var def = this.getDefinition();
return def.instanceLinks ? Object.keys(def.instanceLinks) : [];
};
/**
* @return {Array} The list of static link names.
*/
Resource.prototype.getStaticLinkNames = function() {
var def = this.getDefinition();
return def.staticLinks ? Object.keys(def.staticLinks) : [];
};
/**
* Sends a single object instance response.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Array} objs The array of objects to send.
* @param {Function} [postMapper] Optional Array.map callback that will be called with each raw object instance.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.singleResponse = function(req,res,obj,postMapper,next) {
var response = this.getMapper(postMapper, 1)(obj);
res.send(response);
if(typeof(next) === 'function') {
next(null,response);
}
};
Resource.prototype._listResponse = function(linkGenerator,req,res,objs,postMapper,next) {
instanceLinkNames = this.getInstanceLinkNames(),
rel = this.getRel();
init = this.getDefinition();// TODO
leaf = this.getLeaf();
content = this.getContent();
otype = this.getOType();
oname = this.getOName();
// console.log(leaf)
if(leaf){
var response = {
"@odata.id": rel,
// "@odata.type": "#ManagerCollection.ManagerCollection",
Members: objs.map(this.getMapper(postMapper, 0)),
"[email protected]": objs.map(this.getMapper(postMapper, 0)).length,
"Name": oname
},
qDef = req.$odataQueryDefinition;
response._links = linkGenerator(req,response);
// console.log(qDef && qDef.$top)
if(qDef && qDef.$top) {
// next,prev links
response._links = response._links||{};
// looks odd but $top could be part of the service definition so
// if its there use it but over-ride if supplied by the client.
var forwardArgs = Object.assign({$top: qDef.$top},req.query),
nextArgs = Object.assign({},forwardArgs,{$skip:(parseInt(forwardArgs.$skip||0)+parseInt(forwardArgs.$top))})
prevArgs = Object.assign({},forwardArgs,{$skip:(parseInt(forwardArgs.$skip||0)-parseInt(forwardArgs.$top))}),
baseUrl = req.originalUrl.replace(/\?.*$/,'');
if(prevArgs.$skip >= 0) {
response._links.prev = baseUrl+'?'+querystring.stringify(prevArgs);
}
// only add the next link if there are exactly the requested number of objects.
// can't be sure if the next page might not be empty.
if(response.list.length === parseInt(qDef.$top)){
response._links.next = baseUrl+'?'+querystring.stringify(nextArgs);
}
}
}
else{
var response = {
"@odata.id": rel,
"@odata.type": otype
};
response = Object.assign(response, content);
response.name = oname
}
res.send(response);
if(typeof(next) === 'function') {
next(null,response);
}
};
Resource.prototype._findListResponse = function(req,res,objs,postMapper,next) {
var rel = this.getRel(),
links = this.getStaticLinkNames(),
def = this.getDefinition();
this._listResponse(function(){
if(links.length) {
var lnks = links.reduce(function(map,link){
map[link] = rel+'/'+link;
return map;
},{});
if(def.count && lnks.count) {
var q = Object.assign({},(req.query||{}));
delete q.$top;
delete q.$skip;
delete q.$orderby;
if(Object.keys(q).length) {
lnks.count += '?'+querystring.stringify(q);
}
} else if (!def.count) {
delete lnks.count;
}
return lnks;
}
},req,res,objs,postMapper,next);
};
/**
* Sends a list response.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Array} objs The array of objects to send.
* @param {Function} [postMapper] Optional Array.map callback that will be called with each raw object instance.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.listResponse = function(req,res,objs,postMapper,next) {
var rel = this.getRel(),
links = this.getStaticLinkNames();
this._listResponse(function(){
if(links.length) {
return links.reduce(function(map,link){
if(link !== 'count') {
map[link] = rel+'/'+link;
}
return map;
},{});
}
},req,res,objs,postMapper,next);
};
/**
* Sends a list response when a relationship is traversed. This is used for standard relationships to allow the
* static count link to be handled.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Array} objs The array of objects to send.
* @param {Function} [postMapper] Optional Array.map callback that will be called with each raw object instance.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.relListResponse = function(req,res,objs,postMapper,next) {
var rel = this.getRel(),
links = this.getStaticLinkNames(),
def = this.getDefinition()
this._listResponse(function(){
var lnks = links.reduce(function(map,link){
map[link] = rel+'/'+link;
return map;
},{});
if(def.count) {
// replace count
var q = Object.assign({},(req.query||{}));
delete q.$top;
delete q.$skip;
delete q.$orderby;
if(Object.keys(q).length) {
lnks.count = req.originalUrl.substring(0,req.originalUrl.indexOf('?'))+'/count?'+querystring.stringify(q);
} else {
q = req.originalUrl.indexOf('?');
lnks.count = (q !== -1 ? req.originalUrl.substring(0,q) : req.originalUrl)+'/count';
}
} else {
delete lnks.count;
}
return lnks;
},req,res,objs,postMapper,next);
};
/* not js-doc, don't want in output.
* Translates an Odata $orderby clause into a mongo version.
* http://www.odata.org/documentation/odata-version-2-0/uri-conventions/ (section 4.2)
*
* @param {String} $orderby The external odata $orderby clause
* @return {String} The string equivalent of mongoose sort.
*/
function odataOrderBy($orderby) {
if($orderby) {
var mongo,
clauseExp = /^([^\s]+)\s*(asc|desc|)$/;
$orderby.split(',').forEach(function(clause) {
var clause_parts = clauseExp.exec(clause.trim());
if(!clause_parts) {
debug('orderby clause "%s" invalid, ignoring.',clause);
} else {
var field = clause_parts[1],
direction = clause_parts[2];
if(direction === 'desc') {
field = '-'+field;
}
mongo = mongo ? (mongo+' '+field) : field;
}
});
debug('translated odata orderby "%s" to mongo sort "%s"',$orderby,mongo);
return mongo;
}
}
/**
* Initializes a mongoose query from a user request.
*
* @param {Object} query The mongoose query.
* @param {Object} req The express request object.
* @return {Object} The mongoose query (query input argument).
*/
Resource.prototype.initQuery = function(query,req) {
var base = this.getDefinition(),
def = Object.assign({
$orderbyPaged: '_id',
$expand: base.populate // populate is deprecated, if set its the default for $expand
},base,req.query),
populate = def.$expand ?
(Array.isArray(def.$expand) ? def.$expand : [def.$expand]) : [];
populate.forEach(function(att){
if(typeof(att) === 'string') {
att.split(',').forEach(function(a) {
a = a.trim();
// nested expand, needs to be turned into an object instructing
// which paths/nested paths to expand
if(a.indexOf('.') !== -1) {
var parts = a.split('.'),
pop = { path: parts[0] },cpop = pop,i;
for(i = 1; i < parts.length; i++) {
cpop.populate = { path: parts[i] };
cpop = cpop.populate;
}
a = pop;
}
query.populate(a);
});
} else {
query.populate(att);
}
});
if(base.$select) {
// don't let the caller over-ride to gain access to
// fields that weren't intended.
def.$select = base.$select;
}
if(def.$select) {
query.select(def.$select);
}
if(typeof(def.lean) === 'boolean') {
query.lean(def.lean);
} else {
query.lean(true); // by default go straight to a JavaScript object
}
if(def.$top) {
query.limit(+def.$top);
}
if(def.$skip) {
query.skip(+def.$skip);
}
if(def.$orderby) {
query.sort(odataOrderBy(def.$orderby));
} else if (def.$top) {
// per the odata spec if the client is paging but not sorting then
// we must impose a sort order to ensure responses are repeatable and
// paged results are valid, _id is the only attribute we can count on
// existing so sort on it.
query.sort(def.$orderbyPaged);
}
if(def.$filter) {
filterParser(query,def.$filter);
}
// save the query definiton for later re-use.
req.$odataQueryDefinition = def;
return query;
};
/**
* <p>Builds a 'mapper' object that can be used to translate mongoose objects into
* REST response objects. This function can be passed to Array.map given an array of
* mongoose objects. All object results returned to a client should pass through a
* mapper so that meta information like instance links can be attached.</p>
*
* <p><em>Note:</em> When sending custom responses you should use the [listResponse]{@link Resource#listResponse} or [singleResponse]{@link Resource#singleResponse} functions to do
* so and those functions implicitly use a mapper.</p>
*
* @param {function} postMapper Array.map callback that should be called after the underlying mapper does its work (optional).
* @return {function} An Array.map callback.
*/
Resource.prototype.getMapper = function(postMapper, findType) {
var model = this.getModel(),
instanceLinkNames = this.getInstanceLinkNames(),
rel = this.getRel();
init = this.getDefinition();
okey = this.getOKey();
return function(o,i,arr) {
if(typeof(o.toObject) === 'function') {
if(!i) {
// just log for single maps, or the first in an array.
debug('%s: translating mongoose model to a pojo',rel);
}
o = o.toObject();
}
o["@odata.type"] = init["@odata.type"]
id_sub = String(o._id).substring(String(o._id).length - 8);
var selfLink = rel+'/'+encodeURIComponent(o[okey].replace(/\./g, '_')),
links = {
self: selfLink
};
instanceLinkNames.forEach(function(link) {
links[link] = selfLink+'/'+link
});
o["@odata.id"] = selfLink;
k = {
"@odata.id": selfLink
};
if(findType){
return typeof(postMapper) === 'function' ? postMapper(o,i,arr) : o;
}
else{
return typeof(postMapper) === 'function' ? postMapper(o,i,arr) : k;
}
};
};
/**
* Fetches and returns to the client an entity by id. Resources may
* override this default functionality.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.findById = function(req,res,next) {
var self = this,
def = this.getDefinition();
query = this.initQuery(self.getModel().findById(req._resourceId),req);
query.exec(function(err,obj){
if(err || !obj) {
Resource.sendError(res,404,'not found',err);
} else {
self.singleResponse(req,res,obj,null,next);
}
});
};
/**
* Fetches and returns to the client an entity by parameters. Resources may
* override this default functionality.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.findByOKey = function(req,res,next) {
var self = this,
def = this.getDefinition();
okey = this.getOKey();
resourceId = decodeURIComponent(req._resourceId.replace(/_/g, '.'))
query = this.initQuery(self.getModel().find({[okey]:resourceId}),req);
query.exec(function(err,obj){
if(err || !obj) {
Resource.sendError(res,404,'not found',err);
} else {
self.singleResponse(req,res,obj[0],null,next);
}
});
};
/**
* Executes a query for an entity type and returns the response to the client.
* Resources may override this default functionality.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.find = function(req,res,next) {
var self = this,
def = this.getDefinition(),
query = this.initQuery(self.getModel().find(),req);
query.exec(function(err,objs){
if(err){
Resource.sendError(res,500,'find failed',err);
} else {
debug('found %d objects.', objs.length);
self._findListResponse(req,res,objs,null,next);
}
});
};
/**
* Executes a query for an entity type and returns the response to the client.
* Resources may override this default functionality.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.internalNode = function(req,res,next) {
var self = this
self._findListResponse(req,res,null,null,next);
};
/**
* Executes a query for an entity type and returns the number of objects found.
* Resources may override this default functionality.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
*/
Resource.prototype.count = function(req,res) {
var self = this,
def = this.getDefinition(),
query = this.initQuery(self.getModel().find(),req);
query.countDocuments(function(err,n){
if(err){
Resource.sendError(res,500,'find failed',err);
} else {
res.json(n);
}
});
};
/**
* Creates an instance of this entity type and returns the newly created
* object to the client.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.create = function(req,res,next) {
var self = this,
Model = self.getModel(),
instance = new Model(req.body);
instance.save(function(err,saved){
if(err) {
return Resource.sendError(res,500,'create failure',err,next);
}
// self.singleResponse(req,res,saved);
// re-fetch the object so that nested attributes are properly populated.
req._resourceId = saved._id;
self.findById(req,res,next);
});
};
/**
* <p>Updates an instance of this entity type and returns the updated
* object to the client.</p>
*
* <p><em>Note:</em> This implementation of update is more similar to PATCH in that
* it doesn't require a complete object to update. It will accept a sparsely populated
* input object and update only the keys found within that object.</p>
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.update = function(req,res,next) {
var self = this,
model = self.getModel();
// not using findOneAndUpdate because helpers are not applied
model.findOne({_id: req._resourceId},function(err,obj){
if(err) {
return Resource.sendError(res,404,'not found',err,next);
}
Object.keys(req.body).forEach(function(key){
obj[key] = req.body[key];
});
obj.save(function(err,obj) {
if(err) {
return Resource.sendError(res,500,'update failure',err,next);
}
// re-fetch the object so that nested attributes are properly populated.
self.findById(req,res,next);
});
});
};
/**
* <p>Updates an instance of this entity type and returns the updated
* object to the client.</p>
*
* <p><em>Note:</em> This implementation of update is more similar to PATCH in that
* it doesn't require a complete object to update. It will accept a sparsely populated
* input object and update only the keys found within that object.</p>
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after the response is sent with the response object.
*/
Resource.prototype.action = function(req,res,next) { // TODO
var self = this,
model = self.getModel();
return Resource.sendError(res,500,'update failure',"err",next);
// not using findOneAndUpdate because helpers are not applied
// model.findOne({_id: req._resourceId},function(err,obj){
// if(err) {
// return Resource.sendError(res,404,'not found',err,next);
// }
// Object.keys(req.body).forEach(function(key){
// obj[key] = req.body[key];
// });
// obj.save(function(err,obj) {
// if(err) {
// return Resource.sendError(res,500,'update failure',err,next);
// }
// // re-fetch the object so that nested attributes are properly populated.
// self.findById(req,res,next);
// });
// });
};
/**
* Deletes an instance of this entity type.
*
* @param {Object} req The express request object.
* @param {Object} res The express response object.
* @param {Function} [next] Optional next callback to invoke after successful delete with the model object.
*/
Resource.prototype.delete = function(req,res,next) {
var self = this,
query = self.initQuery(self.getModel().findById(req._resourceId),req);
query.lean(false); // need the object itself regardless of how the resource is defined
query.exec(function(err,obj){
if(err || !obj) {
return Resource.sendError(res,404,'not found',err,next);
}
obj.remove(function(err,obj){
if(err) {
return Resource.sendError(res,500,'remove error',err,next);
}
res.status(200).send();
if(typeof(next) === 'function') {
next(null,obj);
}
});
});
};
/**
* Add a static link implementation to this resource.
*
* @param {String} rel The relative path of the link.
* @param {function} link A function to call when the static link is requested. The
* arguments are (req,res) which are the express request and response
* objects respectively.
* @return {Object} this
*/
Resource.prototype.staticLink = function(rel,link) {
// for now static links are functions only
var def = this._definition,
links = def.staticLinks;
if(!links) {
links = def.staticLinks = {};
}
links[rel] = link;
return this;
};
/**
* Add an instance link to this resource.
*
* The link argument can be either an object defining a simple relationship
* (based on a reference from the 'other side' object) or a function to be called to
* resolve the relationship.
*
* If a function is supplied then its arguments must be (req,res) which are the express
* request and response objects respectively.
*
* If an object is supplied then the necessary keys are:
* - otherSide (Object): The Resource instance of the other side entity.
* - key (string): The attribute name on the otherside object containing the id of this Resource's entity type.
*
* @param {String} rel The relative path of the link.
* @param {Object|function} link The link definition.
* @return {Object} this
*/
Resource.prototype.instanceLink = function(rel,link) {
var def = this._definition,
links = def.instanceLinks;
if(!links) {
links = def.instanceLinks = {};
}
links[rel] = link;
return this;
}
/**
* Initializes and returns an express router.
* If app is supplied then app.use is called to bind the
* resource's 'rel' to the router.
*
* @param {object} app Express app (optional).
* @return {object} Express router configured for this resource.
*/
Resource.prototype.initRouter = function(app) {
var self = this,
resource = self._definition,
router = express.Router();
leaf = this.getLeaf();
if(resource.staticLinks) {
Object.keys(resource.staticLinks).forEach(function(link){
var linkObj = resource.staticLinks[link],
linkObjType = typeof(linkObj);
if(linkObjType === 'function') {
router.get('/'+link,(function(self){
return function(req,res) {
linkObj.apply(self,arguments);
};
})(self));
}
});
}
router.param('id',function(req,res,next,id){
req._resourceId = id;
next();
});
if(typeof(resource.action) === 'undefined' || resource.action) {
resource.create = false
resource.update = false
resource.delete = false
router.post('/:id/' + resource.actionkey,(function(self){
return function(req,res) {
self.action(req,res);
};
})(this));
}
if(typeof(resource.create) === 'undefined' || resource.create) {
router.post('/',(function(self){
return function(req,res) {
self.create(req,res);
};
})(this));
}
if(typeof(resource.update) === 'undefined' || resource.update) {
router.put('/:id',(function(self){
return function(req,res) {
self.update(req,res);
};
})(this));
}
if(typeof(resource.delete) === 'undefined' || resource.delete) {
router.delete('/:id',(function(self){
return function(req,res) {
self.delete(req,res);
};
})(this));
}
if(leaf){
router.get('/:id',(function(self){
return function(req,res) {
self.findByOKey(req,res);
};
})(this));
router.get('/', (function(self){
return function(req,res) {
self.find(req,res);
};
})(this));
}
else{
router.get('/', (function(self){
return function(req,res) {
self.internalNode(req,res);
};
})(this));
}
if(resource.instanceLinks) {
Object.keys(resource.instanceLinks).forEach(function(link){
var linkObj = resource.instanceLinks[link],
linkObjType = typeof(linkObj);
if(linkObjType === 'function') {
router.get('/:id/'+link,(function(self){
return function(req,res) {
resource.instanceLinks[link].apply(self,arguments);
};
})(self));
} else if(linkObj.otherSide instanceof Resource && linkObj.key) {
if(linkObj.otherSide.getDefinition().count) {
router.get('/:id/'+link+'/count',
(function(self,otherSide,key) {
return function(req,res) {
var criteria = {};
criteria[key] = req._resourceId;
var query = otherSide.initQuery(otherSide.getModel().find(criteria),req);
query.countDocuments(function(err,n){
if(err) {
return Resource.sendError(res,500,'error resolving relationship',err)
}
res.json(n);
});
};
})(self,linkObj.otherSide,linkObj.key));
}
router.get('/:id/'+link,
(function(self,otherSide,key) {
return function(req,res) {
var criteria = {};
criteria[key] = req._resourceId;
var query = otherSide.initQuery(otherSide.getModel().find(criteria),req);
query.exec(function(err,objs){
if(err) {
return Resource.sendError(res,500,'error resolving relationship',err)
}
otherSide.relListResponse(req,res,objs);
});
};
})(self,linkObj.otherSide,linkObj.key));
}
});
}
if(app) {
app.use(this.getRel(),router);
}
return router;
};
module.exports = Resource;