1
+ 'use strict' ;
2
+
3
+ /**
4
+ * Module dependencies.
5
+ */
6
+ var mongoose = require ( 'mongoose' ) ,
7
+ errorHandler = require ( './errors.server.controller' ) ,
8
+ Article = mongoose . model ( 'Article' ) ,
9
+ _ = require ( 'lodash' ) ;
10
+
11
+ /**
12
+ * Create a article
13
+ */
14
+ exports . create = function ( req , res ) {
15
+
16
+ var article = new Article ( req . body ) ;
17
+ article . user = req . user ;
18
+
19
+ article . save ( function ( err ) {
20
+ if ( err ) {
21
+ return res . status ( 400 ) . send ( {
22
+ message : errorHandler . getErrorMessage ( err )
23
+ } ) ;
24
+ } else {
25
+ res . json ( article ) ;
26
+ }
27
+ } ) ;
28
+ } ;
29
+
30
+ /**
31
+ * Show the current article
32
+ */
33
+ exports . read = function ( req , res ) {
34
+ res . json ( req . article ) ;
35
+ } ;
36
+
37
+ /**
38
+ * Update a article
39
+ */
40
+ exports . update = function ( req , res ) {
41
+ var article = req . article ;
42
+
43
+ article = _ . extend ( article , req . body ) ;
44
+
45
+ article . save ( function ( err ) {
46
+ if ( err ) {
47
+ return res . status ( 400 ) . send ( {
48
+ message : errorHandler . getErrorMessage ( err )
49
+ } ) ;
50
+ } else {
51
+ res . json ( article ) ;
52
+ }
53
+ } ) ;
54
+ } ;
55
+
56
+ /**
57
+ * Delete an article
58
+ */
59
+ exports . delete = function ( req , res ) {
60
+ var article = req . article ;
61
+
62
+ article . remove ( function ( err ) {
63
+ if ( err ) {
64
+ return res . status ( 400 ) . send ( {
65
+ message : errorHandler . getErrorMessage ( err )
66
+ } ) ;
67
+ } else {
68
+ res . json ( article ) ;
69
+ }
70
+ } ) ;
71
+ } ;
72
+
73
+ /**
74
+ * List of Articles
75
+ */
76
+ exports . list = function ( req , res ) {
77
+ Article . find ( ) . sort ( '-created' ) . populate ( 'user' , 'displayName' ) . exec ( function ( err , articles ) {
78
+ if ( err ) {
79
+ return res . status ( 400 ) . send ( {
80
+ message : errorHandler . getErrorMessage ( err )
81
+ } ) ;
82
+ } else {
83
+ res . json ( articles ) ;
84
+ }
85
+ } ) ;
86
+ } ;
87
+
88
+ /**
89
+ * Article middleware
90
+ */
91
+ exports . articleByID = function ( req , res , next , id ) {
92
+ Article . findById ( id ) . populate ( 'user' , 'displayName' ) . exec ( function ( err , article ) {
93
+ if ( err ) return next ( err ) ;
94
+ if ( ! article ) return next ( new Error ( 'Failed to load article ' + id ) ) ;
95
+ req . article = article ;
96
+ next ( ) ;
97
+ } ) ;
98
+ } ;
99
+
100
+ /**
101
+ * Article authorization middleware
102
+ */
103
+ exports . hasAuthorization = function ( req , res , next ) {
104
+ if ( req . article . user . id !== req . user . id ) {
105
+ return res . status ( 403 ) . send ( {
106
+ message : 'User is not authorized'
107
+ } ) ;
108
+ }
109
+ next ( ) ;
110
+ } ;
0 commit comments