/
documentation.html
executable file
·2082 lines (1899 loc) · 65.3 KB
/
documentation.html
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
<!DOCTYPE html>
<html lang="en" ng-app="percdocs">
<head>
<meta charset="utf-8">
<title>percolator.js</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<link href="css/sh_acid.min.css" rel="stylesheet">
<!-- body {
padding-top: 60px;
padding-bottom: 40px;
}
.nav-list > li > a {
padding: 0px 0px 0px 0px;
margin-left : 10px;
}
-->
<style type="text/css">
body {
padding-top: 40px;
}
section {
padding-top: 40px;
}
.navbar .nav li {
margin-bottom: 0px;
}
.nav-header {
padding-top: 5px;
padding-bottom: 5px;
margin-top: 0px;
margin-bottom: 0px;
}
.nav-sub-header {
font-size: 12px;
margin-left : 15px;
margin-top: 0px;
margin-bottom: 0px;
}
p.nav-sub-header {
margin-left : 30px;
}
li.nav-header {
margin-top : 0px;
padding-top : 0px;
padding-bottom : 0px;
}
</style>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="ico/apple-touch-icon-57-precomposed.png">
<script type="text/javascript" src="/js/sh_main.min.js"></script>
<script type="text/javascript" src="/js/sh_javascript.min.js"></script>
</head>
<body onload="sh_highlightDocument();" >
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="/"><img src="/img/headr-nav.png" /></a>
<div class="nav-collapse collapse">
<ul class="nav">
<li><a href="/">Home</a></li>
<li><a href="about.html">About</a></li>
<li class="active"><a href="documentation.html">Documentation</a></li>
<li><a href="examples.html">Examples</a></li>
<li><a href="https://github.com/cainus/percolator">Source Code</a></li>
</ul>
</div><!--/.nav-collapse -->
</div><!-- /container -->
</div><!-- /navbar-inner -->
</div><!-- /navbar -->
<div class="container" id="topspacer">
</div>
<div class="container">
<h2>
Documentation
</h2>
<p></p>
<ul class="nav nav-list">
<li class="nav-header"><a href="#installation">Installation</a></li>
<li class="nav-header" ><a href="#runningtests">Running Tests</a></li>
<li class="nav-header" ><a href="#helloworld">Hello World Quick Start</a></li>
<li class="nav-header"><a href="#server">The Percolator Server Object</a></li>
<p class="nav-sub-header">
<a href="#server-route">route</a>
<a href="#server-listen">listen</a>
<a href="#server-before">before</a>
<a href="#server-after">after</a>
<a href="#server-connectmiddleware">connectMiddleware</a>
</p>
<li class="nav-header" ><a href="#handler">The Handler Object</a></li>
<li class="nav-sub-header"><a href="#handler-GET">GET</a></li>
<li class="nav-sub-header"><a href="#handler-POST">POST</a></li>
<li class="nav-sub-header"><a href="#handler-DELETE">DELETE</a></li>
<li class="nav-sub-header"><a href="#handler-PUT">PUT</a></li>
<li class="nav-sub-header"><a href="#handler-fetch">fetch</a></li>
<li class="nav-sub-header"><a href="#handler-authenticate">authenticate</a></li>
<li class="nav-sub-header"><a href="#handler-basicAuthenticate">basicAuthenticate</a></li>
<li class="nav-header"><a href="#req-uri">req.uri</a></li>
<p class="nav-sub-header">
<a href="#req-uri-child">child</a>
<a href="#req-uri-decode">decode</a>
<a href="#req-uri-encode">encode</a>
<a href="#req-uri-hash">hash</a>
<a href="#req-uri-hostname">hostname</a>
<a href="#req-uri-parent">parent</a>
<a href="#req-uri-password">password</a>
<a href="#req-uri-path">path</a>
<a href="#req-uri-port">port</a>
<a href="#req-uri-protocol">protocol</a>
<a href="#req-uri-query">query</a>
<a href="#req-uri-querystring">queryString</a>
<a href="#req-uri-toJson">toJson</a>
<a href="#req-uri-toString">toString</a>
<a href="#req-uri-username">username</a>
</p>
<li class="nav-header" ><a href="#req-onJson">req.onJson</a></li>
<li class="nav-header" ><a href="#req-onBody">req.onBody</a></li>
<li class="nav-header" ><a href="#res-object">res.object</a></li>
<p class="nav-sub-header">
<a href="#res-object-toString">toString</a>
<a href="#res-object-toObject">toObject</a>
<a href="#res-object-property">property</a>
<a href="#res-object-link">link</a>
<a href="#res-object-send">send</a>
</p>
<li class="nav-header" ><a href="#res-collection">res.collection</a></li>
<p class="nav-sub-header">
<a href="#res-collection-each">each</a>
<a href="#res-collection-linkEach">linkEach</a>
</p>
<li class="nav-header"><a href="#res-status">res.status</a></li>
<p class="nav-sub-header">
<a href="#res-status-created">created</a>
<a href="#res-status-accepted">accepted</a>
<a href="#res-status-noContent">noContent</a>
<a href="#res-status-resetContent">resetContent</a>
<a href="#res-status-movedPermanently">movedPermanently</a>
<a href="#res-status-redirect">redirect</a>
<a href="#res-status-badRequest">badRequest</a>
<a href="#res-status-unauthenticated">unauthenticated</a>
<a href="#res-status-forbidden">forbidden</a>
<a href="#res-status-notFound">notFound</a>
<a href="#res-status-methodNotAllowed">methodNotAllowed</a>
<a href="#res-status-notAcceptable">notAcceptable</a>
<a href="#res-status-conflict">conflict</a>
<a href="#res-status-gone">gone</a>
<a href="#res-status-lengthRequired">lengthRequired</a>
<a href="#res-status-preconditionFailed">preconditionFailed</a>
<a href="#res-status-requestEntityTooLarge">requestEntityTooLarge</a>
<a href="#res-status-requestUriTooLong">requestUriTooLong</a>
<a href="#res-status-unsupportedMediaType">unsupportedMediaType</a>
<a href="#res-status-unprocessableEntity">unprocessableEntity</a>
<a href="#res-status-tooManyRequests">tooManyRequests</a>
<a href="#res-status-internalServerError">internalServerError</a>
<a href="#res-status-notImplemented">notImplemented</a>
<a href="#res-status-badGateway">badGateway</a>
<a href="#res-status-serviceUnavailable">serviceUnavailable</a>
<a href="#res-status-gatewayTimeout">gatewayTimeout</a>
</p>
<li class="nav-header" ><a href="#crudCollection">CRUDCollection</a></li>
<p class="nav-sub-header">
<a href="#crudCollection-list">list</a>
<a href="#crudCollection-fetch">fetch</a>
<a href="#crudCollection-create">create</a>
<a href="#crudCollection-update">update</a>
<a href="#crudCollection-upsert">upsert</a>
<a href="#crudCollection-destroy">destroy</a>
<a href="#crudCollection-collectionGET">collectionGET</a>
<a href="#crudCollection-memberGET">memberGET</a>
<a href="#crudCollection-updateSchema">updateSchema</a>
<a href="#crudCollection-createSchema">createSchema</a>
<a href="#crudCollection-schema">schema</a>
</p>
<li class="nav-header" ><a href="#advancedrouting">Advanced Routing</a> </li>
</ul>
<section id="installation">
<h3>Installation</h3>
<code>npm install percolator</code>
</section>
<section id="runningtests">
<h3>Running Tests</h3>
<code>make test</code>
</section>
<section id="helloworld">
<h3>Hello World Quick Start:</h3>
<ul class="unstyled">
<li> Create a <code class="incode">server.js</code> in your project directory, and copy this code below into it:</li>
<pre class="sh_javascript">
var Percolator = require('percolator').Percolator;
var server = new Percolator();
server.route('/hello', { GET : function(req, res){
res.object({message : 'Hello World!'}).send();
}});
server.listen(function(err){
console.log('server is listening on port ', server.port);
});
</pre>
<li>
<p>Run the server:
<code class="incode">node server.js</code>
</p>
</li>
<li><p>See your "Hello World" output at http://localhost:3000/hello and be completely floored by the greatest
API of all time. Or not.</p>
The output json look like this:
<pre class="sh_javascript">
{
message: "Hello World!",
_links: {
parent: {
href: "http://localhost:3000/"
}
}
}
</pre >
<p>You'll notice that Percolator automatically adds a link to the document itself. This is because
it tries to help you create a surfable "Hypermedia" API where every endpoint is accessible from a link
in another endpoint, and where everything that can be done with the API is described in the API
itself.</p>
<p>
See the <a href="https://github.com/cainus/hyper-json-spec">spec for the hyper+json media type</a> for more details on how Percolator outputs its links by default.
</p>
</li>
</ul>
</section>
<div class="alert alert-success">
<h3>Why should I care about Hypermedia??!?</h3>
<p>
Because Hypermedia APIs are pretty awesome for the people using your API.
</p>
<p>
Developers can find their way to all your endpoints just by following the links in the json payload
instead of having to read a bunch of docs. Using a browser plugin like JSONView for
<a href="http://jsonview.com/">Firefox</a> or
<a href="https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc">chrome</a>
makes it so developers can just surf around your API in their browser as if your
responses are regular web pages.
</p>
<p>
These types of APIs are machine-readable as well, so they're spider-able, and even allow automatic
form generation, or automated fuzz-testing.
</p>
<p>
In other frameworks adding links everywhere can be time-consuming. Percolator makes this either
automatic or very easy though.
</p>
<p>
NOTE: If you're worried about the size of your responses, keep in mind that
with proper caching and compression (gzip), there should be little to no cost to your
clients' performance or bandwidth.
</p>
<p>
If you're still unconvinced, you can just pass <code class="incode">autoLink : false</code> to the
Percolator constructor, and no links will be added automatically.
</p>
</div> <!-- /alert -->
<section id="server">
<h3>The Percolator Server Object</h3>
Any Percolator objects you create are just http servers (based on
<a href="https://github.com/cainus/oneone">oneone</a>) with a bunch of helpers
for making JSON APIs more easily.
<h5>The constructor</h5>
The constructor returns a percolator server. It can take an optional single object as
a parameter like so:
<pre class="sh_javascript">
var server = new Percolator({"some" : "object"});
</pre>
<p>
This is called the <strong>app</strong> object.
</p>
<p>
Anything you put in the app object will be available to all your HTTP handlers as req.app, so it's
great for shared configuration, database objects, etc.
</p>
<p>Additionally, the constructor recognizes a few special properties of the app object:</p>
<p>
<strong>protocol</strong> - 'http' or 'https'<br>
<strong>resourcePath</strong> - the url path that all the resource will be routed from (eg. Setting it to '/' will serve the
resources from <a href="http://yourdomain.com/">http://yourdomain.com/</a> while setting it to '/api' will serve the resources from
<a href="http://yourdomain.com/api">http://yourdomain.com/api</a> .<br>
<strong>staticDir</strong> - The directory on the filesystem from which you will serve static content (use an absolute path!).<br><strong>port</strong> - the http port. A low port like 80 will not work unless you run the app with root privileges. </p>
<strong>autoLink</strong> - A boolean that indicates whether or not to automatically add some links to your json payloads for you. This value is optional, and the default is 'true', meaning that hyperlinks will be added automatically to your json payloads.<br>
<strong>port</strong> - the http port. A low port like 80 will not work unless you run the app with root privileges. <br>
<strong>key</strong> - the key for https. If you're not doing https, this is ignored.<br>
<strong>cert</strong> - the cert for https. If you're not doing https, this is ignored.<br>
<strong>pfx</strong> - the pfx for https. If you're not doing https, this is ignored.<br>
<strong>parseBody</strong> - A boolean that indicates whether or not to automatically wait for the entire body to stream in before
calling an HTTP method handler. If set to true, the body will be available as req.rawBody or parsed as json to an object available as req.body . The default for this is false,
because the <a href="#req-onBody">req.onBody</a> and <a href="#req-onJson">req.onJson</a> functions allow you to access the same data on a case-by-case basis. It's recommended that you try those first.
</p>
<p>You're obviously going to want to limit the number of app object variables that you add beyond the necessary ones, but
certain types of objects might make sense in that shared space.</p>
<section id="server-route">
<h5>route(routeString, handler)</h5>
<p>
The route() method of the server takes two parameters, the route string and the resource object.
</p>
<p>
It then sets a route using the route string that the given <a href="#handler">handler object</a> will handle when
an incoming request matches that route.
</p>
<p>
Route strings can be regular expressions, or
<a href="http://expressjs.com/api.html">express</a>/sinatra-style route strings.
</p>
<p>
The resource object is any object that has methods on it that match HTTP methods like POST, PUT, GET,
DELETE, etc. The method takes the standard req and res parameters.
</p>
<p>
The Hello World example above has a resource object that implements only GET:
</p>
<pre class="sh_javascript">
{
GET : function(req, res){
res.object({message : 'Hello World!'}).send();
}
}
</pre>
Of course, other HTTP methods (PUT, POST, DELETE, etc) can be added to this object as well to
make this API do more. Here it is, passed to route() with a routeString of '/', the root path:
<pre class="sh_javascript">
server.route('/', { GET : function(req, res){
res.object({message : 'Hello World!'}).send();
}});
</pre>
Here it is with a POST handler as well:
<pre class="sh_javascript">
server.route('/', {
GET : function(req, res){
res.object({message : 'Hello World!'}).send();
},
POST : function(req, res){
req.onJson(function(err, obj){
res.object({posted:obj}).send();
});
}
});
</pre>
Note that because resource objects are just objects, you can load them from a file as modules, or create
components that you re-use for different modules.
</section>
<section id="server-listen">
<h5>listen([cb])</h5>
Call listen() on the server to start it listening. The default port (unless overridden by
the app object) is 3000.
listen() takes an optional callback as well, that is called when the server is listening, or
when there's been an error. The error will be the first parameter to this callback, if it exists.
<pre class="sh_javascript">
server.listen(function(err){
console.log('server is listening on port ', server.port);
});
</pre>
</section>
<section id="server-before">
<h5>before(cb)</h5>
<p>
The before() method takes a callback as its only parameter. The callback is called when
a request occurs.
</p>
<p>
The callback takes req, res, handler and cb parameters.
</p>
<p>
The <strong>req and res</strong> parameters are the standard node request and response objects.
If you want to augment them for some reason, for all requests, this is a great place to do it.
</p>
<p>
The <strong>handler</strong> is the resource object that is routed to the request url in
the router. It will contain the functions meant to handle the different HTTP methods.
</p>
<p>
The <strong>cb</strong> parameter is a callback that will be called to signal that pre-processing
is complete.
</p>
<p>
Here's an example:
</p>
<pre class="sh_javascript">
server.before(function(req, res, handler, cb){
// print the request method and url before every request.
console.log(' <-- ', req.method, ' ', req.url);
cb();
});
</pre>
</section>
<section id="server-after">
<h5>after(cb)</h5>
<p>
The after() method takes a callback as its only parameter. The callback is called after a
response is ended.
</p>
<p>
The callback takes req and res parameters.
</p>
<p>
The <strong>req and res</strong> parameters are the standard node request and response objects.
If you want to augment them for some reason, for all requests, this is a great place to do it.
</p>
<p>
Here's an example:
</p>
<pre class="sh_javascript">
server.after(function(req, res){
// print the request method and url after every request.
console.log(' <-- ', req.method, ' ', req.url);
});
</pre>
</section>
<section id="server-connectmiddleware">
<h5>connectMiddleware(middleware)</h5>
<p>
The connectMiddleware() method takes a <a href="http://www.senchalabs.org/connect/">connect compatible middleware</a> as its only parameter.
</p>
<p>
Here's an example:
</p>
<pre class="sh_javascript">
server.connectMiddleware(connect.favicon());
// add the favicon middleware to the percolator server
</pre>
</section>
</section>
<section id="handler">
<h3>The Handler Object</h3>
<p>The handler object is not an object in the Percolator framework, but rather is one that an application
written on the Percolator framework should provide for each route that it defines. It is simply the
object that is passed to calls to <a href="#server-route">Server.route()</a> that specifies how a route should handle requests.
</p>
<p>
It may or may not implement any of the methods listed below. If it does not implement a particular HTTP method, requests to the handler for that
method will result in an automatic 405 (method not allowed) response.</p>
<section id="handler-GET"></section>
<h5>GET(req, res)</h5>
<p>
Implementing this method on a handler object will allow it to respond to GET requests. The only
parameters are the standard request and response objects from node. Any return value will be ignored.
</p>
<section id="handler-POST"></section>
<h5>POST(req, res)</h5>
<p>
Implementing this method on a handler object will allow it to respond to POST requests. The only
parameters are the standard request and response objects from node. Any return value will be ignored.
</p>
<section id="handler-DELETE"></section>
<h5>DELETE(req, res)</h5>
<p>
Implementing this method on a handler object will allow it to respond to DELETE requests. The only
parameters are the standard request and response objects from node. Any return value will be ignored.
</p>
<section id="handler-PUT"></section>
<h5>PUT(req, res)</h5>
<p>
Implementing this method on a handler object will allow it to respond to PUT requests. The only
parameters are the standard request and response objects from node. Any return value will be ignored.
</p>
<section id="handler-authenticate"></section>
<h5>authenticate(req, res, cb)</h5>
<p>
Implementing authenticate() is not required but is convenient if you want
to specify a general authentication strategy for all methods on the resource.
If you implement authenticate(), it will automatically return 401 responses for
unauthenticated access while permitting authenticated access as normal.
<p>The authenticate() function has three required parameters: the standard req and res parameters
, and a callback (cb).</p>
<p>The <strong>cb</strong> argument is a callback that takes two parameters. The
first parameter is an error object if any error occurred. If the error object
is strictly <strong>true</strong>, then the response will be a 401. If the error
object is non-strict-true but still truthy, then the response will be a 500 (internal
server error). The second parameter should be an object that represents the
logged in user. It will automatically
by added to the req object as req.authenticated in any member resource
methods that you implement.
</p>
<pre class="sh_javascript">
server.route('/someProtectedPath', {
authenticate : function(req, res, cb){
// try to get the user here, based on cookie, Authentication header, etc
if (cannotGetUser){
return cb(true); // Percolator will 401 for you
}
cb(someError, theUser);
// if there wasn't some other error, theUser will be available
// at req.authenticated in all methods
},
GET : function(req, res){
res.object({youAre : req.authenticated}).send();
}
});
</pre>
<section id="handler-basicAuthenticate"></section>
<h5>basicAuthenticate(username, password, req, res, cb)</h5>
<p>
Implementing basicAuthenticate() is not required but is convenient if you want
to use <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">basic http authentication</a>
on the resource. If you implement basicAuthenticate(), it will automatically return 401 responses for
unauthenticated access while permitting authenticated access as normal.
<p>The basicAuthenticate() function has five required parameters: the basic http auth username,
the basic http auth password, the standard node req and res objects, and a callback, cb.</p>
<p>The <strong>cb</strong> argument is a callback that takes two parameters. The
first parameter is an error object if any error occurred. If the error object
is strictly <strong>true</strong>, then the response will be a 401. If the error
object is non-strict-true but still truthy, then the response will be a 500 (internal
server error). The second parameter should be an object that represents the
logged in user. It will automatically
by added to the req object as req.authenticated in any member resource
methods that you implement.
</p>
<pre class="sh_javascript">
server.route('/someProtectedPath', {
basicAuthenticate : function(username, password, req, res, cb){
// try to get the user here, based on cookie, Authentication header, etc
if (username === 'Pierre' && password === 'Collateur'){
return cb(null, {username : "Pierre", twitter_handle : "@Percolator"});
// user object will be available in req.authenticated in all methods
} else {
return cb(true); // Percolator will 401 for you
}
},
GET : function(req, res){
res.object({youAre : req.authenticated}).send();
}
});
</pre>
<section id="handler-fetch"></section>
<h5>fetch(req, res, cb)</h5>
<p>
Implementing fetch() on a handler object is an unnecessary but sometimes useful way to specify how
404s will be determined, so you don't need to write the same 404-handling code in all methods
that you support. If you implement fetch(), fetch can do the 404-ing for you, before your regular
handler methods are even run. In the event of a 404, a call to <a href="#res-status-notFound">res.status.notFound()
</a> will be made automatically.
</p>
<p>The fetch() function has three required parameters: the standard node req and res objects,
and a callback (cb).</p>
<p>The <strong>cb</strong> argument is a callback that takes two parameters. The
first parameter is an error object if any error occurred. The
second parameter should be the object that was fetched from your
data source for the current uri. It will automatically
by added to the req object as req.fetched in any member resource
methods that you implement.
</p>
<p>
The fetch() function will 404 for you automatically if you
pass strict <strong>true</strong> to the callback (<strong>
cb</strong>) as the first parameter.
</p>
<p>
A handler object can also have a boolean property by the name of 'fetchOnPUT' that defaults to true,
but allows you to turn fetch off for PUT, even though fetch usually applies to all methods. This
is useful if you use PUT for creating new resources at the given URL, because a non-existent
resource would otherwise cause a 404.
</p>
<pre class="sh_javascript">
var module = new CRUDCollection({
fetch : function(req, res, cb){
// get some item from your data source, probably based on req.uri.child()
cb(null, theObject);
}
});
</pre>
</section>
</section>
<section id="res-status">
</section>
<h5>res.status</h5>
<p>
The status module is automatically attached to your resource handler at request time. It is just a bunch of helper functions for dealing with response statuses.
</p>
<p>
This is an important module because building great APIs requires excellent and consistent error and status reporting.
</p>
<p>
To understand what the codes mean, please refer to <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html</a>.
</p>
<h6>Usage</h6>
These methods generally set the HTTP status and end the response, so in general you should
not expect to write more to the response after these. If a response body makes sense, it
will generally be written automatically. For clarity, it's recommended that when you call
one of these functions, you call it with <code class="incode">return</code> in front of it. Here's an example:
<pre class="sh_javascript">
server.route('/', { GET : function(req, res){
return res.status.redirect('/someOtherUrl');
}});
</pre>
<p>
Here are the functions that it makes available in your method handler:
</p>
<h6>Redirect scenarios</h6>
<section id="res-status-created">
<dl>
<dt>
res.status.created(redirectUrl);
</dt>
<dd>
This method is used for HTTP STATUS 201 scenarios when the server has just created a resource successfully so that the server can tell the client where to find it. It sets the status to 201 and sets the 'Location' header to the redirectUrl.
</dd>
</dl>
</section>
<section id="res-status-movedPermanently">
<dl>
<dt>
res.status.movedPermanently(redirectUrl);
</dt>
<dd>
This method is used for HTTP STATUS 301 scenarios where a resource has been permanently moved somewhere else so the server can tell the client where to find it. It sets the status to 301 and sets the 'Location' header to the redirectUrl.
</dd>
</dl>
</section>
<section id="res-status-redirect">
<dl>
<dt>
res.status.redirect(redirectUrl);
</dt>
<dd>
This is just an alias of movedPermanently()
</dd>
</dl>
</section>
<h6>Success responses</h6>
<p>
"200 OK" statuses are the default, so you don't need to specify those explicitly.
</p>
<p>
201 Created statuses are described in the redirect section above.
</p>
<section id="res-status-accepted">
<dl>
<dt>
res.status.accepted();
</dt>
<dd>
Used to indicate that a response has been accepted, but not yet processed, this response will emit a "202 Accepted" status.
</dd>
</dl>
</section>
<section id="res-status-noContent">
<dl>
<dt>
res.status.noContent();
</dt>
<dd>
Used to indicate that a request was successful, but there's no body to return (for example, a successful DELETE). This response will emit a "204 No Content" status.
</dd>
</dl>
</section>
<section id="res-status-resetContent">
<dl>
<dt>
req.status.resetContent();
</dt>
<dd>
Used to indicate that a request was sucessful so a related UI (usually a form) should clear its content. This response will emit a "205 Reset Content" status.
</dd>
</dl>
</section>
<h6>Error Scenarios</h6>
All of the error scenarios are handled similarly and attempt to show a response body that indicates the error that occurred as well. The status code will be set on the response as well as in that response body.
All of these methods additionally take a single parameter where additional detail information can be added. For example:
<pre class="sh_javascript">
server.route('/', { GET : function(req, res){
return res.status.internalServerError('The server is on fire.');
}});
</pre>
Output:<br />
<code>
{"type":500,"message":"Internal Server Error","detail":"The server is on fire"}
</code>
<h6>Error response methods:</h6>
<section id="res-status-badRequest">
<dl>
<dt>
res.status.badRequest([detail])
</dt>
<dd>
<code>
{"type":400,"message":"Bad Request"}
</code>
</dd>
</dl>
</section>
<section id="res-status-unauthenticated">
<dl>
<dt>
res.status.unauthenticated([detail])
</dt>
<dd>
<code>
{"type":401,"message":"Unauthenticated"}
</code>
</dd>
</dl>
</section>
<section id="res-status-forbidden">
<dl>
<dt>
res.status.forbidden([detail])
</dt>
<dd>
<code>
{"type":403,"message":"Forbidden"}
</code>
</dd>
</dl>
</section>
<section id="res-status-notFound">
<dl>
<dt>
res.status.notFound([detail])
</dt>
<dd>
<code>
{"type":404,"message":"Not Found"}
</code>
</dd>
</dl>
</section>
<section id="res-status-methodNotAllowed">
<dl>
<dt>
res.status.methodNotAllowed([detail])
</dt>
<dd>
<code>
{"type":405,"message":"Method Not Allowed"}
</code>
</dd>
</dl>
</section>
<section id="res-status-notAcceptable">
<dl>
<dt>
res.status.notAcceptable([detail])
</dt>
<dd>
<code>
{"type":406,"message":"Not Acceptable"}
</code>
</dd>
</dl>
</section>
<section id="res-status-conflict">
<dl>
<dt>
res.status.conflict([detail])
</dt>
<dd>
<code>
{"type":409,"message":"Conflict"}
</code>
</dd>
</dl>
</section>
<section id="res-status-gone">
<dl>
<dt>
res.status.gone([detail])
</dt>
<dd>
<code>
{"type":410,"message":"Gone"}
</code>
</dd>
</dl>
</section>
<section id="res-status-lengthRequired">
<dl>
<dt>
res.status.lengthRequired([detail])
</dt>
<dd>
<code>
{"type":411,"message":"Length Required"}
</code>
</dd>
</dl>
</section>
<section id="res-status-preconditionFailed">
<dl>
<dt>
res.status.preconditionFailed([detail])
</dt>
<dd>
<code>
{"type":412,"message":"Precondition Failed"}
</code>
</dd>
</dl>
</section>
<section id="res-status-requestEntityTooLarge">
<dl>
<dt>
res.status.requestEntityTooLarge([detail])
</dt>
<dd>
<code>
{"type":413,"message":"'Request Entity Too Large"}
</code>
</dd>
</dl>
</section>
<section id="res-status-requestUriTooLong">
<dl>
<dt>
res.status.requestUriTooLong([detail])
</dt>
<dd>
<code>
{"type":414,"message":"Request URI Too Long"}
</code>
</dd>
</dl>
</section>
<section id="res-status-unsupportedMediaType">
<dl>
<dt>
res.status.unsupportedMediaType([detail])
</dt>
<dd>
<code>
{"type":415,"message":"Unsupported Media Type"}
</code>
</dd>
</dl>
</section>
<section id="res-status-unprocessableEntity">
<dl>
<dt>
res.status.unprocessableEntity([detail])
</dt>
<dd>
<code>
{"type":422,"message":"'Unprocessable Entity"}
</code>
</dd>
</dl>
</section>
<section id="res-status-tooManyRequests">
<dl>
<dt>
res.status.tooManyRequests([detail])
</dt>
<dd>
<code>
{"type":429,"message":"Too Many Requests"}
</code>
</dd>
</dl>
</section>
<section id="res-status-internalServerError">
<dl>
<dt>
res.status.internalServerError([detail])
</dt>
<dd>
<code>
{"type":500,"message":"Internal Server Error"}
</code>
</dd>
</dl>
</section>
<section id="res-status-notImplemented">
<dl>
<dt>
res.status.notImplemented([detail])
</dt>
<dd>
<code>
{"type":501,"message":"Not Implemented"}
</code>
</dd>
</dl>
</section>
<section id="res-status-badGateway">
<dl>
<dt>
res.status.badGateway([detail])
</dt>
<dd>
<code>
{"type":502,"message":"Bad Gateway"}
</code>
</dd>
</dl>
</section>
<section id="res-status-serviceUnavailable">
<dl>