1
+ import { Router , Request , Response , NextFunction } from "express" ;
2
+ import Post from '../models/Post' ;
3
+
4
+
5
+ export class PostRouter {
6
+
7
+ router : Router ;
8
+
9
+ constructor ( ) {
10
+ this . router = Router ( ) ;
11
+ this . routes ( ) ;
12
+ }
13
+
14
+ public getAllPosts ( req : Request , res : Response , next : NextFunction ) {
15
+ Post . find ( )
16
+ . then ( ( posts ) => {
17
+ res . status ( 200 ) . json ( { posts } ) ;
18
+ } )
19
+ . catch ( ( error ) => {
20
+ res . status ( 500 ) . json ( { error } ) ;
21
+ } )
22
+ }
23
+
24
+ public getPostBySlug ( req : Request , res : Response , next : NextFunction ) {
25
+ const slug = req . params . slug ;
26
+
27
+ Post . findOne ( { slug} )
28
+ . then ( ( post ) => {
29
+ res . status ( 200 ) . json ( { post } ) ;
30
+ } )
31
+ . catch ( ( error ) => {
32
+ res . status ( 500 ) . json ( { error } ) ;
33
+ } )
34
+ }
35
+
36
+
37
+ // create post
38
+ public createPost ( req : Request , res : Response , next : NextFunction ) : void {
39
+ const title = req . body . title ;
40
+ const slug = req . body . slug ;
41
+ const content = req . body . content ;
42
+
43
+ if ( ! title || ! slug || ! content ) {
44
+ res . status ( 422 ) . json ( { message : 'All Fields Required.' } ) ;
45
+ }
46
+
47
+ const post = new Post ( {
48
+ title,
49
+ slug,
50
+ content
51
+ } ) ;
52
+
53
+ post . save ( )
54
+ . then ( ( post ) => {
55
+ res . status ( 200 ) . json ( { post } ) ;
56
+ } )
57
+ . catch ( ( error ) => {
58
+ res . status ( 500 ) . json ( { error } ) ;
59
+ } )
60
+ }
61
+
62
+
63
+ // update post by slug
64
+ public updatePost ( req : Request , res : Response , next : NextFunction ) : void {
65
+ const slug = req . body . slug ;
66
+
67
+ Post . findOneAndUpdate ( { slug} , req . body )
68
+ . then ( ( post ) => {
69
+ res . status ( 200 ) . json ( { post } ) ;
70
+ } )
71
+ . catch ( ( error ) => {
72
+ res . status ( 500 ) . json ( { error } ) ;
73
+ } )
74
+ }
75
+
76
+
77
+ // delete post by slug
78
+ public deletePost ( req : Request , res : Response , next : NextFunction ) : void {
79
+ const slug = req . body . slug ;
80
+
81
+ Post . findOneAndRemove ( { slug} )
82
+ . then ( ( post ) => {
83
+ res . status ( 200 ) . json ( { post } ) ;
84
+ } )
85
+ . catch ( ( error ) => {
86
+ res . status ( 500 ) . json ( { error } ) ;
87
+ } )
88
+ }
89
+
90
+
91
+
92
+ routes ( ) {
93
+ this . router . get ( '/' , this . getAllPosts ) ;
94
+ this . router . get ( '/:slug' , this . getPostBySlug ) ;
95
+ this . router . post ( '/' , this . createPost ) ;
96
+ this . router . put ( '/:slug' , this . updatePost ) ;
97
+ this . router . delete ( '/:slug' , this . deletePost ) ;
98
+ }
99
+
100
+
101
+ }
102
+
103
+ const postRoutes = new PostRouter ( ) ;
104
+ postRoutes . routes ( ) ;
105
+
106
+ export default postRoutes . router ;
0 commit comments