1
+ const { Router } = require ( "express" ) ;
2
+ const { destroy } = require ( "./../database/models/Post" ) ;
3
+ const router = Router ( ) ;
4
+ // REQUERIR EL MODELO
5
+ // const Post = require('./../database/models/Post');
6
+ const Post = require ( './../database/models/Post' ) ;
7
+
8
+
9
+
10
+ // RETORNAR TODOS
11
+ /*
12
+ http://localhost:3006/api/posts
13
+ */
14
+ router . get ( '/' , ( req , res ) => {
15
+
16
+ Post . findAll ( ) . then ( posts => {
17
+ res . json ( posts ) ;
18
+ } )
19
+
20
+ } ) ;
21
+
22
+
23
+
24
+ // RETORNAR SOLO UNO POR EL ID
25
+ /*
26
+ http://localhost:3006/api/posts/1
27
+ */
28
+ router . get ( '/:id' , ( req , res ) => {
29
+ Post . findByPk ( req . params . id ) . then ( post => {
30
+ res . json ( post ) ;
31
+ } )
32
+ } ) ;
33
+
34
+
35
+ // CREAR
36
+ /*
37
+ http://localhost:3006/api/posts
38
+ Content-Type application/json
39
+ {
40
+ "title" : "Nuevo 2",
41
+ "body": "Nuevo desde post 2"
42
+ }
43
+ */
44
+ router . post ( '/' , ( req , res ) => {
45
+
46
+ Post . create ( {
47
+ title : req . body . title ,
48
+ body : req . body . body
49
+ } ) . then ( post => {
50
+ res . json ( post ) ;
51
+ } ) . catch ( error => {
52
+ console . log ( "Ocurrio error al guardar: " , error ) ;
53
+ res . json ( { status : error } )
54
+ } )
55
+
56
+ } ) ;
57
+
58
+
59
+
60
+ // ACTUALIZAR
61
+ /*
62
+ http://localhost:3006/api/posts/1
63
+ Content-Type application/json
64
+ {
65
+ "title" : "Nuevo 2",
66
+ "body": "Nuevo desde post 2"
67
+ }
68
+ */
69
+ router . patch ( '/:id' , ( req , res ) => {
70
+
71
+ Post . update ( {
72
+ title : req . body . title ,
73
+ body : req . body . body
74
+ } , {
75
+ where : {
76
+ id : req . params . id
77
+ }
78
+ } ) . then ( result => {
79
+ res . json ( result ) ;
80
+ } ) ;
81
+
82
+ } ) ;
83
+
84
+
85
+
86
+ // ELIMINAR
87
+ /*
88
+ http://localhost:3006/api/posts/1
89
+ */
90
+ router . delete ( '/:id' , ( req , res ) => {
91
+
92
+ Post . destroy ( {
93
+ where :{
94
+ id : req . params . id
95
+ }
96
+ } ) . then ( result => {
97
+ res . json ( result ) ;
98
+ } )
99
+
100
+ } ) ;
101
+
102
+
103
+
104
+ module . exports = router ;
0 commit comments