-
Notifications
You must be signed in to change notification settings - Fork 1
/
REST API
1670 lines (1643 loc) · 78.9 KB
/
REST API
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
controllers/controllers/index.js
module.exports = {
BookSales: require("./booksales"),
Stores: require("./stores"),
Employees: require("./employees"),
ClientReviews: require("./clientreviews"),
Clients: require("./clients"),
Books: require("./books"),
Authors: require("./authors")
}
This file is used to export each controller. Using this technique lets us import the entire folder as if it is a module:
var controllers = require("/controllers")
/controllers/basecontroller.js
var _ = require("underscore"),
restify = require("restify"),
colors = require("colors"),
halson = require("halson")
function BaseController() {
this.actions = []
this.server = null
}
BaseController.prototype.setUpActions = function(app, sw) {
this.server = app
_.each(this.actions, function(act) {
var method = act['spec']['method']
//a bit of a logging message, to help us understand what’s going on under the hood
console.log("Setting up auto-doc for (", method, ") - ", act['spec']['nickname'])
sw['add' + method](act)
app[method.toLowerCase()](act['spec']['path'], act['action']) }) }
BaseController.prototype.addAction = function(spec, fn) {
var newAct = { 'spec': spec,
action: fn }
this.actions.push(newAct) }
BaseController.prototype.RESTError = function(type, msg) {
if(restify[type]) {
return new restify[type](msg.toString())
} else {
console.log("Type " + type + " of error not found".red)
} }
/** Takes care of calling the "toHAL" method on every resource before writing it
back to the client */ BaseController.prototype.writeHAL = function(res, obj) {
if(Array.isArray(obj)) {
var newArr = []
_.each(obj, function(item, k) {
item = item.toHAL()
newArr.push(item) })
obj = halson (newArr) }
else {
if(obj && obj.toHAL)
obj = obj.toHAL() }
if(!obj) {
obj = {}
}
res.json(obj) }
module.exports = BaseController
Every controller extends this object, gaining access to the methods shown earlier.
We’ll use basic prototypical inheritance, as you’ll see in a bit when we start listing the other controllers’ code.
As for this one, let’s
quickly go over the methods it exposes:
setUpActions: This method is called upon instantiation of the controller; it is meant to add the actual routes to the HTTP server.
This method is called during the initialization sequence for all controllers exported by the index.js file.
addAction: This method defines an action, which consists of the specs for that action and the actual function code.
The specs are used by Swagger to create the documentation,
but they’re also used by our code to set up the route; so there are bits inside the JSON spec that are also meant for the server,
such as the path and method attributes.
RESTError: This is a simple wrapper method around all the error methods provided by Restify.1 It provides the benefit of cleaner code.
writeHAL: Every model defined (as you’ll see next) has a toHAL method, and the writeHAL methods take care of calling it for every model we’re trying to render.
It basically centralizes the logic that deals with collections or simple objects, depending on what we’re trying to render.
TipWe’re using the colors module here to print the error message from the RESTError method in red./controllers/books.js
var BaseController = require("./basecontroller"),
_ = require("underscore"),
swagger = require("swagger-node-restify")
function Books() { }
Books.prototype = new BaseController()
module.exports = function(lib) {
var controller = new Books();
/** Helper function for the POST action */
function mergeStores(list1, list2) {
var stores1 = {}
var stores2 = {}
_.each(list1, function(st) {
if(st.store)
stores1[st.store] = st.copies
})
_.each(list2, function(st) {
if(st.store)
stores2[st.store] = st.copies })
var stores = _.extend(stores1, stores2)
return _.map(stores, function(v, k) {
return {store: k, copies: v} })
}
controller.addAction({
'path': '/books',
'method': 'GET',
'summary': 'Returns the list of books',
"params": [ swagger.queryParam('q', 'Search term', 'string'), swagger.queryParam('genre','Filter by genre', 'string')],
'responseClass': 'Book',
'nickname': 'getBooks'
}, function(req, res, next) {
var criteria = {}
if(req.params.q) {
var expr = new RegExp('.*' + req.params.q + '.*')
criteria.$or = [
{title: expr},
{isbn_code: expr},
{description: expr}
] }
if(req.params.genre) {
criteria.genre = req.params.genre
}
lib.db.model('Book')
.find(criteria)
.populate('stores.store')
.exec(function(err, books) {
if(err) return next(err)
controller.writeHAL(res, books)
}) })
controller.addAction({
'path': '/books/{id}',
'method': 'GET',
'params': [ swagger.pathParam('id', 'The Id of the book','int') ],
'summary': 'Returns the full data of a book',
'nickname': 'getBook'
}, function(req, res, next) {
var id = req.params.id
if(id) {
lib.db.model("Book")
.findOne({_id: id})
.populate('authors')
.populate('stores')
.populate('reviews')
.exec(function(err, book) {
if(err) return
next(controller.RESTError('InternalServerError', err))
if(!book) {
return
next(controller.RESTError('ResourceNotFoundError', 'Book not found'))
}
controller.writeHAL(res, book)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Missing book id'))
}
})
controller.addAction({
'path': '/books',
'method': 'POST',
'params': [ swagger.bodyParam('book', 'JSON representation of the new book','string') ],
'summary': 'Adds a new book into the collectoin',
'nickname': 'newBook'
}, function(req, res, next) {
var bookData = req.body
if(bookData) {
isbn = bookData.isbn_code
lib.db.model("Book")
.findOne({isbn_code: isbn})
.exec(function(err, bookModel) {
if(!bookModel) {
bookModel = lib.db.model("Book")(bookData)
} else {
bookModel.stores = mergeStores(bookModel.stores, bookData.stores)
}
bookModel.save(function(err, book) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, book)
}) })
} else {
next(controller.RESTError('InvalidArgumentError', 'Missing content of book'))
}
})
controller.addAction({
'path': '/books/{id}/authors',
'method': 'GET',
'params': [ swagger.pathParam('id', 'The Id of the book','int') ],
'summary': 'Returns the list of authors of one specific book',
'nickname': 'getBooksAuthors'
}, function(req, res, next) {
var id = req.params.id
if(id) {
lib.db.model("Book")
.findOne({_id: id})
.populate('authors')
.exec(function(err, book) {
if(err) return next(controller.RESTError('InternalServerError', err))
if(!book) {
return
next(controller.RESTError('ResourceNotFoundError', 'Book not found'))
}
controller.writeHAL(res, book.authors)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Missing book id'))
} })
controller.addAction({
'path': '/books/{id}/reviews',
'method': 'GET',
'params': [ swagger.pathParam('id', 'The Id of the book','int') ],
'summary': 'Returns the list of reviews of one specific book',
'nickname': 'getBooksReviews'
}, function(req, res,next) {
var id = req.params.id
if(id) {
lib.db.model("Book")
.findOne({_id: id})
.populate('reviews')
.exec(function(err, book) {
if(err) return next(controller.RESTError('InternalServerError', err))
if(!book) {
return
next(controller.RESTError('ResourceNotFoundError', 'Book not found'))
}
controller.writeHAL(res, book.reviews)
}) }
else {
next(controller.RESTError('InvalidArgumentError', 'Missing book id'))
} })
controller.addAction({
'path': '/books/{id}',
'method': 'PUT',
'params': [ swagger.pathParam('id', 'The Id of the book to update','string'),
swagger.bodyParam('book', 'The data to change on the book', 'string') ],
'summary': 'Updates the information of one specific book',
'nickname': 'updateBook'
}, function(req, res, next) {
var data = req.body
var id = req.params.id
if(id) {
lib.db.model("Book").findOne({_id: id}).exec(function(err, book)
{
if(err) return
next(controller.RESTError('InternalServerError', err))
if(!book)
return
next(controller.RESTError('ResourceNotFoundError', 'Book not found'))
book = _.extend(book, data)
book.save(function(err, data) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, data.toJSON())
})
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id received'))
} })
return controller }
The code for this controller is very straightforward;
in it are the basic mechanics defined for this particular project on how to declare a controller and its actions.
We also have a special case for the POST action,
which checks the ISBN of a new book to see if it is in stock at another store.
If an ISBN already exists, the book is merged to all relevant stores;
otherwise, a new record is created.In theory, we’re creating a new function that inherits from the BaseController,
which gives us the ability to add custom behavior on a specific controller.
Reality is going to prove that we don’t really need such liberties,
however. And we could very well do the same by instantiating the BaseController directly on every other controller file.The controller files are required during initialization of the API, and when that happens, the lib object is passed to them, like so:
var controller = require("/controllers/books.js")(lib)
This means that (as you see in the preceding code),
the lib object is received by the export function,
which is in charge of instantiating the new controller and adding actions to it to return it to the required code.
Here are some other interesting bits from the code:
The getBooks action shows how to do simple regular expression–based filtering with Mongoose.
The update action is not actually using the update method from Mongoose,
but instead loads the model using the extend method from the underscore,
and finally calls the save method on the model.
This is done for one simple reason: the update method doesn’t trigger any post hooks on the models,
but the save method does,
so if we wanted to add behavior to react to an update on the model, this would be the way to go about it.
/controllers/stores.js
var BaseController = require("./basecontroller"),
_ = require("underscore"),
swagger = require("swagger-node-restify")
function Stores() {
}
Stores.prototype = new BaseController()
module.exports = function(lib) {
var controller = new Stores();
controller.addAction({
'path': '/stores',
'method': 'GET',
'summary': 'Returns the list of stores ',
'params': [swagger.queryParam('state', 'Filter the list of stores by state', 'string')],
'responseClass': 'Store',
'nickname': 'getStores'
}, function (req, res, next) {
var criteria = {}
if(req.params.state) {
criteria.state = new RegExp(req.params.state,'i')
}
lib.db.model('Store')
.find(criteria)
.exec(function(err, list) {
if(err)
return
next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, list)
}) })
controller.addAction({
'path': '/stores/{id}',
'method': 'GET',
'params': [swagger.pathParam('id','The id of the store','string')],
'summary': 'Returns the data of a store',
'responseClass': 'Store',
'nickname': 'getStore'
}, function(req, res, next) {
var id = req.params.id
if(id) {
lib.db.model('Store')
.findOne({_id: id})
.populate('employees')
.exec(function(err, data) {
if(err) return
next(controller.RESTError('InternalServerError', err))
if(!data) return
next(controller.RESTError('ResourceNotFoundError', 'Store not found'))
controller.writeHAL(res, data)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id'))
}
})
controller.addAction({
'path': '/stores/{id}/books',
'method': 'GET',
'params': [swagger.pathParam('id','The id of the store','string'),
swagger.queryParam('q', 'Search parameter for the books', 'string'),
swagger.queryParam('genre', 'Filter results by genre', 'string')],
'summary': 'Returns the list of books of a store',
'responseClass': 'Book',
'nickname': 'getStoresBooks'
}, function (req, res, next) {
var id = req.params.id
if(id) {
var criteria = {stores: id}
if(req.params.q) {
var expr = new RegExp('.*' + req.params.q + '.*', 'i')
criteria.$or = [
{title: expr},
{isbn_code: expr},
{description: expr} ]
}
if(req.params.genre) {
criteria.genre = req.params.genre
}
//even though this is the stores controller, we deal directly with books here
lib.db.model('Book')
.find(criteria)
.populate('authors')
.exec(function(err, data) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, data)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id'))
}
})
controller.addAction({
'path': '/stores/{id}/employees',
'method': 'GET',
'params': [swagger.pathParam('id','The id of the store','string')],
'summary': 'Returns the list of employees working on a store',
'responseClass': 'Employee',
'nickname': 'getStoresEmployees'
}, function (req, res, next) {
var id = req.params.id
if(id) {
lib.db.model('Store')
.findOne({_id: id})
.populate('employees')
.exec(function(err, data) {
if(err)
return
next(controller.RESTError('InternalServerError', err))
if(!data) {
return
next(controller.RESTError('ResourceNotFoundError', 'Store not found'))
}
console.log(data)
controller.writeHAL(res, data.employees)
}) } else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id'))
}
})
controller.addAction({
'path': '/stores/{id}/booksales',
'method': 'GET',
'params': [swagger.pathParam('id','The id of the store','string')],
'summary': 'Returns the list of booksales done on a store',
'responseClass': 'BookSale',
'nickname': 'getStoresBookSales'
}, function (req, res, next) {
var id = req.params.id
if(id) {
//even though this is the stores controller, we deal directly with booksales here
lib.db.model('Booksale')
.find({store: id})
.populate('client')
.populate('employee')
.populate('books')
.exec(function(err, data) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, data)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id'))
}
})
controller.addAction({
'path': '/stores',
'method': 'POST',
'summary': 'Adds a new store to the list',
'params': [swagger.bodyParam('store', 'The JSON data of the store', 'string')],
'responseClass': 'Store',
'nickname': 'newStore'
}, function (req, res, next) {
var data = req.body
if(data) {
var newStore = lib.db.model('Store')(data)
newStore.save(function(err, store) {
if(err) return next(controller.RESTError('InternalServerError', err))
res.json(controller.toHAL(store))
})
} else {
next(controller.RESTError('InvalidArgumentError', 'No data received'))
}
})
controller.addAction({
'path': '/stores/{id}',
'method': 'PUT',
'summary': "UPDATES a store's information",
'params': [swagger.pathParam('id','The id of the store','string'),
swagger.bodyParam('store', 'The new information to update', 'string')],
'responseClass': 'Store',
'nickname': 'updateStore'
}, function (req, res, next) {
var data = req.body
var id = req.params.id
if(id) {
lib.db.model("Store").findOne({_id: id}).exec(function(err, store) {
if(err) return next(controller.RESTError('InternalServerError', err))
if(!store) return next(controller.RESTError('ResourceNotFoundError', 'Store not found'))
store = _.extend(store, data)
store.save(function(err, data) {
if(err) return next(controller.RESTError('InternalServerError', err))
res.json(controller.toHAL(data)) })
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id received'))
}
})
return controller
}
The code for the Stores controller is very similar to that of the Books controller. It does, however,
have something of notice:
the getStoresBookSales action clearly shows what happens when we don’t use a Hierarchical MVC model.
I said that this is not a common case,
so it would be fine for the purpose of this book,
but it shows how separation of concerns is broken in the strictest of senses by acting over the model of another controller,
instead of going through that other controller.
Given the added complexity that mechanism would imply to our code,
we’re better off looking the other way for the time being.Here are the remaining controllers.
They don’t particularly show anything new compared to the previous ones,
so just look at the code and the occasional code comment./controllers/authors.js
var BaseController = require("./basecontroller"),
swagger = require("swagger-node-restify")
function BookSales() {
}
BookSales.prototype = new BaseController()
module.exports = function(lib) {
var controller = new BookSales()
//list
controller.addAction({
'path': '/authors', 4
'method': 'GET',
'summary' :'Returns the list of authors across all stores',
'params': [ swagger.queryParam('genre', 'Filter authors by genre of their books', 'string'),
swagger.queryParam('q', 'Search parameter', 'string')],
'responseClass': 'Author',
'nickname': 'getAuthors'
}, function(req, res, next) {
var criteria = {}
if(req.params.q) {
var expr = new RegExp('.*' + req.params.q + '.*', 'i')
criteria.$or = [
{name: expr},
{description: expr}
]
}
var filterByGenre = false || req.params.genre
if(filterByGenre) {
lib.db.model('Book')
.find({genre: filterByGenre})
.exec(function(err, books) {
if(err)
return
next(controller.RESTError('InternalServerError', err))
findAuthors(_.pluck(books, '_id'))
})
} else {
findAuthors()
}
function findAuthors(bookIds) {
if(bookIds) {
criteria.books = {$in: bookIds}
}
lib.db.model('Author')
.find(criteria)
.exec(function(err, authors) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, authors)
})
}
})
//get
controller.addAction({
'path': '/authors/{id}',
'summary': 'Returns all the data from one specific author',
'method': 'GET',
'responseClass': 'Author',
'nickname': 'getAuthor'
}, function (req, res, next) {
var id = req.params.id
if(id) {
lib.db.model('Author')
.findOne({_id: id})
.exec(function(err, author) {
if(err)
return
next(controller.RESTError('InternalServerError', err))
if(!author) {
return
next(controller.RESTError('ResourceNotFoundError', 'Author not found'))
}
controller.writeHAL(res, author)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Missing author id'))
}
})
//post
controller.addAction({
'path': '/authors',
'summary': 'Adds a new author to the database',
'method': 'POST',
'params': [swagger.bodyParam('author', 'JSON representation of the data', 'string')],
'responseClass': 'Author',
'nickname': 'addAuthor'
}, function (req, res, next) {
var body = req.body
if(body) {
var newAuthor = lib.db.model('Author')(body)
newAuthor.save(function(err, author) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, author)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Missing author id'))
} })
//put
controller.addAction({
'path': '/authors/{id}',
'method': 'PUT',
'summary': "UPDATES an author's information",
'params': [swagger.pathParam('id','The id of the author','string'),
swagger.bodyParam('author', 'The new information to update', 'string')],
'responseClass': 'Author',
'nickname': 'updateAuthor'
}, function (req, res, next) {
var data = req.body
var id = req.params.id
if(id) {
lib.db.model("Author").findOne({_id: id}).exec(function(err, author) {
if(err) return next(controller.RESTError('InternalServerError', err))
if(!author) return next(controller.RESTError('ResourceNotFoundError', 'Author not found'))
author = _.extend(author, data)
author.save(function(err, data) {
if(err) return next(controller.RESTError('InternalServerError', err))
res.json(controller.toHAL(data))
})
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id received'))
}
})
// /books
controller.addAction({
'path': '/authors/{id}/books',
'summary': 'Returns the data from all the books of one specific author',
'method': 'GET',
'params': [ swagger.pathParam('id', 'The id of the author', 'string')],
'responseClass': 'Book',
'nickname': 'getAuthorsBooks'
}, function (req, res, next) {
var id = req.params.id
if(id) {
lib.db.model('Author')
.findOne({_id: id})
.populate('books')
.exec(function(err, author) {
if(err) return next(controller.RESTError('InternalServerError', err))
if(!author) {
return next(controller.RESTError('ResourceNotFoundError', 'Author not found'))
}
controller.writeHAL(res, author.books)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Missing author id'))
}
})
return controller
}
/controllers/booksales.js
var BaseController = require("./basecontroller"),
swagger = require("swagger-node-restify")
function BookSales() { }
BookSales.prototype = new BaseController()
module.exports = function(lib) {
var controller = new BookSales();
controller.addAction({
'path': '/booksales',
'method': 'GET',
'summary': 'Returns the list of book sales',
'params': [ swagger.queryParam('start_date', 'Filter sales done after (or on)
this date', 'string'),
swagger.queryParam('end_date', 'Filter sales done on or before this date', 'string'),
swagger.queryParam('store_id', 'Filter sales done on this store', 'string')
],
'responseClass': 'BookSale',
'nickname': 'getBookSales'
}, function(req, res, next) {
console.log(req)
var criteria = {}
if(req.params.start_date)
criteria.date = {$gte: req.params.start_date}
if(req.params.end_date)
criteria.date = {$lte: req.params.end_date}
if(req.params.store_id)
criteria.store = req.params.store_id
lib.db.model("Booksale")
.find(criteria)
.populate('books')
.populate('client')
.populate('employee')
.populate('store')
.exec(function(err, sales) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, sales)
}) })
controller.addAction({
'path': '/booksales',
'method': 'POST',
'params': [ swagger.bodyParam('booksale', 'JSON representation of the new booksale','string') ],
'summary': 'Records a new booksale',
'nickname': 'newBookSale'
}, function(req, res, next) {
var body = req.body
if(body) {
var newSale = lib.db.model("Booksale")(body)
newSale.save(function(err, sale) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, sale)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Missing json data'))
}
})
return controller
}
/controllers/clientreviews.js
var BaseController = require("./basecontroller"),
_ = require("underscore"),
swagger = require("swagger-node-restify")
function ClientReviews() {
}
ClientReviews.prototype = new BaseController()
module.exports = function(lib) {
var controller = new ClientReviews();
controller.addAction({ 4
'path': '/clientreviews',
'method': 'POST',
'summary': 'Adds a new client review to a book',
'params': [swagger.bodyParam('review', 'The JSON representation of the review', 'string')],
'responseClass': 'ClientReview',
'nickname': 'addClientReview'
}, function (req, res, next) {
var body = req.body
if(body) {
var newReview = lib.db.model('ClientReview')(body)
newReview.save(function (err, rev) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, rev)
})
}
})
return controller
}
/controllers/clients.js
var BaseController = require("./basecontroller"),
_ = require("underscore"),
swagger = require("swagger-node-restify")
function Clients() {
}
Clients.prototype = new BaseController()
module.exports = function(lib) {
var controller = new Clients();
controller.addAction({
'path': '/clients',
'method': 'GET',
'summary': 'Returns the list of clients ordered by name',
'responsClass':'Client',
'nickname': 'getClients'
}, function(req, res, next) {
lib.db.model('Client').find().sort('name').exec(function(err, clients) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, clients)
})
})
controller.addAction({
'path': '/clients',
'method': 'POST',
'params': [swagger.bodyParam('client', 'The JSON representation of the client', 'string')],
'summary': 'Adds a new client to the database',
'responsClass': 'Client',
'nickname': 'addClient'
}, function(req, res, next) {
var newClient = req.body
var newClientModel = lib.db.model('Client')(newClient)
newClientModel.save(function(err, client) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, client)
}) })
controller.addAction({
'path': '/clients/{id}',
'method': 'GET',
'params': [swagger.pathParam('id', 'The id of the client', 'string')],
'summary': 'Returns the data of one client',
'responsClass': 'Client',
'nickname': 'getClient'
}, function (req, res, next) {
var id = req.params.id
if(id != null) {
lib.db.model('Client').findOne({_id: id}).exec(function(err, client){
if(err) return next(controller.RESTError('InternalServerError',err))
if(!client) return next(controller.RESTError('ResourceNotFoundError', 'The client id cannot be found'))
controller.writeHAL(res, client)
})
} else {
next(controller.RESTError('InvalidArgumentError','Invalid client id'))
}
})
controller.addAction({
'path': '/clients/{id}',
'method': 'PUT',
'params': [swagger.pathParam('id', 'The id of the client', 'string'),
swagger.bodyParam('client', 'The content to overwrite', 'string')],
'summary': 'Updates the data of one client',
'responsClass': 'Client',
'nickname': 'updateClient'
}, function (req, res, next) {
var id = req.params.id
if(!id) {
return next(controller.RESTError('InvalidArgumentError','Invalid id'))
} else {
var model = lib.db.model('Client')
model.findOne({_id: id})
.exec(function(err, client) {
if(err) return next(controller.RESTError('InternalServerError', err))
client = _.extend(client, req.body)
client.save(function(err, newClient) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, newClient)
})
})
}
})
return controller
}
/controllers/employees.js
var BaseController = require("./basecontroller"),
_ = require("underscore"),
swagger = require("swagger-node-restify")
function Employees() {
}
Employees.prototype = new BaseController()
module.exports = function(lib) {
var controller = new Employees();
controller.addAction({
'path': '/employees',
'method': 'GET',
'summary': 'Returns the list of employees across all stores',
'responseClass': 'Employee',
'nickname': 'getEmployees'
}, function(req, res, next) {
lib.db.model('Employee').find().exec(function(err, list) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, list)
}) })
controller.addAction({
'path': '/employees/{id}',
'method': 'GET',
'params': [swagger.pathParam('id','The id of the employee','string')],
'summary': 'Returns the data of an employee',
'responseClass': 'Employee',
'nickname': 'getEmployee'
}, function(req, res, next) {
var id = req.params.id
if(id) {
lib.db.model('Employee').findOne({_id: id}).exec(function(err, empl) {
if(err) return next(err)
if(!empl) {
return next(controller.RESTError('ResourceNotFoundError', 'Not found'))
}
controller.writeHAL(res, empl)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'Invalid id'))
} })
controller.addAction({
'path': '/employees',
'method': 'POST',
'params': [swagger.bodyParam('employee', 'The JSON data of the employee', 'string')],
'summary': 'Adds a new employee to the list',
'responseClass': 'Employee',
'nickname': 'newEmployee'
}, function(req, res, next) {
var data = req.body
if(data) {
var newEmployee = lib.db.model('Employee')(data)
newEmployee.save(function(err, emp) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, emp)
})
} else {
next(controller.RESTError('InvalidArgumentError', 'No data received'))
} })
controller.addAction({
'path': '/employees/{id}',
'method': 'PUT',
'summary': "UPDATES an employee's information",
'params': [swagger.pathParam('id','The id of the employee','string'),
swagger.bodyParam('employee', 'The new information to update', 'string')],
'responseClass': 'Employee',
'nickname': 'updateEmployee'
}, function(req, res, next) {
var data = req.body
var id = req.params.id
if(id) {
lib.db.model("Employee").findOne({_id: id}).exec(function(err, emp) {
if(err) return next(controller.RESTError('InternalServerError', err))
emp = _.extend(emp, data)
emp.save(function(err, employee) {
if(err) return next(controller.RESTError('InternalServerError', err))
controller.writeHAL(res, employee)
})
})
} else {
next(controller.RESTError('InvalidArgumentError','Invalid id received'))
}
})
return controller
}
libAs mentioned,
the lib folder contains all sorts of helper functions and utilities that were just too small to be put into a separate folder,
but important and generic enough to be used in several places of the code./lib/index.js
var lib = {
helpers: require("./helpers"),
config: require("./config"),
controllers: require("../controllers"),
schemas: require("../schemas"),
schemaValidator: require("./schemaValidator"),
db: require("./db")
}
module.exports = lib
This file is supposed to act as the single point of contact between the outside world (the rest of the project) and the inside world (all of the mini-modules grouped within this folder).
There is nothing special about it.
It just requires everything and exports using predefined keys./lib/helpers.js
var halson = require("halson"),
_ = require("underscore")
module.exports = {
makeHAL: makeHAL,
setupRoutes: setupRoutes,
validateKey: validateKey
}
function setupRoutes(server, swagger, lib) {
for(controller in lib.controllers) {
cont = lib.controllers[controller](lib)
cont.setUpActions(server, swagger)
} }
/** Makes sure to sign every request and compare it
against the key sent by the client, this way
we make sure its authentic */
function validateKey(hmacdata, key, lib) {
//This is for testing the swagger-ui, should be removed after development to avoid possible security problem :)
if(+key == 777) return true
var hmac = require("crypto").createHmac("md5", lib.config.secretKey)
.update(hmacdata)
.digest("hex");
//TODO: Remove this line
console.log(hmac)
return hmac == key
}
function makeHAL(data, links, embed) {
var obj = halson(data)
if(links && links.length > 0) {
_.each(links, function(lnk) {
obj.addLink(lnk.name, {
href: lnk.href,
title: lnk.title || ''
})
})
}
if(embed && embed.length > 0) {
_.each(embed, function (item) {
obj.addEmbed(item.name, item.data)
}) }
return obj
}
Just as the modules exported by the index.js file are too small to merit their own folder,
these functions are too small and particular to merit their own module,
so instead they are grouped here, inside the helpers module.
The functions are meant to be of use (hence, the name “helpers”) throughout the entire project.L
et’s quickly go over each of these names:
setupRoutes: This function is called from within the project’s main file during boot-up time.
It’s meant to initialize all controllers, which in turn adds the actual route’s code to the HTTP server.
validateKey: This function contains the code to validate the request by recalculating the HMAC key.
And as mentioned earlier, it contains the exception to the rule, allowing any request to validate if the key sent is 777.
makeHAL: This function turns any type of object into a HAL JSON object ready to be rendered.
This particular function is heavily used from within the models’ code.
/lib/schemaValidator.js
var tv4 = require("tv4"),
formats = require("tv4-formats"),
schemas = require("../request_schemas/")
module.exports = {
validateRequest: validate
}
function validate (req) {
var res = {valid: true}
tv4.addFormat(formats)
var schemaKey = req.route ? req.route.path.toString().replace("/", "") : ''
var actionKey = req.route.name
if(schemas[schemaKey]) {
var mySchema = schemas[schemaKey][actionKey]
var data = null
if(mySchema) {
switch(mySchema.validate) {
case 'params':
data = req.params
break
}
res = tv4.validateMultiple(data, mySchema.schema)
} }
return res
}
This file has the code that validates any request against a JSON Schema that we define.
The only function of interest is the validate function, which validates the request object.
It also counts on a predefined structure inside the request,
which is added by Swagger (the route attribute).As you might’ve guessed from the preceding code,
the validation of a request is optional; not every request is being validated. And right now,
only query parameters are validated, but this can be extended by simply adding a new case to the switch statement.
This function works with the premise of “convention over configuration,”
which means that if you set up everything “right,” then you don’t have to do much.
In our particular case, we’re looking inside the request_schemas folder to load a set of predefined schemas,
which have a very specific format.
In that format we find the name of the action (the nickname that we set up) to validate and the portion of the request we want to validate.
In our particular function, we’re only validating query parameters for things such as invalid formats and so forth.
The only request we have set up to validate right now is the BookSales listing action;
but if we wanted to add a new validation, it would just be a matter of adding a new schema—no programming
required./lib/db.js
var config = require("./config"),
_ = require("underscore"),
mongoose = require("mongoose"),
Schema = mongoose.Schema
var obj = {
cachedModels: {},
getModelFromSchema: getModelFromSchema,
model: function(mname) {
return this.models[mname]
},
connect: function(cb) {
mongoose.connect(config.database.host + "/" + config.database.dbname)