@@ -23,18 +23,85 @@ const repository = AppDataSource.getRepository(Content)
23
23
24
24
// GET /contents
25
25
router . get ( '/contents' , async ( req : express . Request , res : express . Response ) => {
26
- const contents = await repository . find ( )
27
- res . send ( contents )
26
+ try {
27
+ const contents = await repository . find ( )
28
+ res . send ( contents )
29
+ } catch ( error ) {
30
+ console . error ( error )
31
+ res . status ( 500 ) . send ( error )
32
+ }
33
+ } )
34
+
35
+ // POST /contents
36
+ router . post ( '/contents' , async ( req : express . Request , res : express . Response ) => {
37
+ try {
38
+ const content = new Content ( req . body . title , req . body . body )
39
+ await repository . save ( content )
40
+ res . send ( content )
41
+ } catch ( error ) {
42
+ console . error ( error )
43
+ res . status ( 500 ) . send ( error )
44
+ }
28
45
} )
29
46
30
47
// GET /contents/:id
31
48
router . get ( '/contents/:id' , async ( req : express . Request , res : express . Response ) => {
32
- const content = await repository . findOne ( {
33
- where : { id : Number ( req . params . id ) } ,
34
- order : { id : 'ASC' } ,
35
- } )
36
- if ( content == null ) res . status ( 404 ) . send ( )
37
- res . send ( content )
49
+ try {
50
+ const content = await repository . findOne ( {
51
+ where : { id : Number ( req . params . id ) } ,
52
+ order : { id : 'ASC' } ,
53
+ } )
54
+ if ( content == null ) {
55
+ res . status ( 404 ) . send ( )
56
+ return
57
+ }
58
+ res . send ( content )
59
+ } catch ( error ) {
60
+ console . error ( error )
61
+ res . status ( 500 ) . send ( error )
62
+ }
63
+ } )
64
+
65
+ // PUT /contents/:id
66
+ router . put ( '/contents/:id' , async ( req : express . Request , res : express . Response ) => {
67
+ try {
68
+ const content = await repository . findOne ( {
69
+ where : { id : Number ( req . params . id ) } ,
70
+ } )
71
+ if ( content == null ) {
72
+ res . status ( 404 ) . send ( )
73
+ return
74
+ }
75
+
76
+ // PATCH的に一部更新も可能とする
77
+ content . title = req . body . title || content . title
78
+ content . body = req . body . body || content . body
79
+
80
+ await repository . save ( content )
81
+ res . send ( content )
82
+ } catch ( error ) {
83
+ console . error ( error )
84
+ res . status ( 500 ) . send ( error )
85
+ }
86
+ } )
87
+
88
+ // DELETE /contents/:id
89
+ router . delete ( '/contents/:id' , async ( req : express . Request , res : express . Response ) => {
90
+ try {
91
+ const content = await repository . findOne ( {
92
+ where : { id : Number ( req . params . id ) } ,
93
+ } )
94
+ if ( content == null ) {
95
+ res . status ( 404 ) . send ( )
96
+ return
97
+ }
98
+
99
+ await repository . remove ( content )
100
+ res . sendStatus ( 204 ) . send ( )
101
+ } catch ( error ) {
102
+ console . error ( error )
103
+ res . status ( 500 ) . send ( error )
104
+ }
38
105
} )
39
106
40
107
app . use ( router )
0 commit comments