@@ -81,5 +81,40 @@ public static void main(String[] args) {
8181 return gson .toJson (new StructuredResponse ("ok" , "" + newId , null ));
8282 }
8383 });
84+
85+ // PUT route for updating a row in the DataStore. This is almost
86+ // exactly the same as POST
87+ Spark .put ("/messages/:id" , (request , response ) -> {
88+ // If we can't get an ID or can't parse the JSON, Spark will send
89+ // a status 500
90+ int idx = Integer .parseInt (request .params ("id" ));
91+ SimpleRequest req = gson .fromJson (request .body (), SimpleRequest .class );
92+ // ensure status 200 OK, with a MIME type of JSON
93+ response .status (200 );
94+ response .type ("application/json" );
95+ DataRow result = dataStore .updateOne (idx , req .mTitle , req .mMessage );
96+ if (result == null ) {
97+ return gson .toJson (new StructuredResponse ("error" , "unable to update row " + idx , null ));
98+ } else {
99+ return gson .toJson (new StructuredResponse ("ok" , null , result ));
100+ }
101+ });
102+
103+ // DELETE route for removing a row from the DataStore
104+ Spark .delete ("/messages/:id" , (request , response ) -> {
105+ // If we can't get an ID, Spark will send a status 500
106+ int idx = Integer .parseInt (request .params ("id" ));
107+ // ensure status 200 OK, with a MIME type of JSON
108+ response .status (200 );
109+ response .type ("application/json" );
110+ // NB: we won't concern ourselves too much with the quality of the
111+ // message sent on a successful delete
112+ boolean result = dataStore .deleteOne (idx );
113+ if (!result ) {
114+ return gson .toJson (new StructuredResponse ("error" , "unable to delete row " + idx , null ));
115+ } else {
116+ return gson .toJson (new StructuredResponse ("ok" , null , null ));
117+ }
118+ });
84119 }
85120}
0 commit comments