fixed post and added delete

This commit is contained in:
2024-06-04 10:04:47 +02:00
parent 9070d1452b
commit 74d421514d
3 changed files with 87 additions and 10 deletions

View File

@@ -230,8 +230,6 @@ public class Routes {
Connection c = null;
PreparedStatement stmt = null;
System.out.println(post);
// try to get data from db
try {
// check for the driver
@@ -245,12 +243,38 @@ public class Routes {
c.setAutoCommit(false);
// create a new statement
stmt = c.prepareStatement("");
stmt = c.prepareStatement("INSERT INTO Posts(author, title, content, postdate, postlocation) " +
"VALUES (?, ?, ?, ?, Point(?, ?)) RETURNING id");
//stmt.setObject();
stmt.setObject(1, post.getAuthorID());
stmt.setObject(2, post.title);
stmt.setObject(3, post.content);
stmt.setObject(4, post.date);
stmt.setObject(5, post.location.longitude);
stmt.setObject(6, post.location.latitude);
// query recursively for posts inside a 10km radius
stmt.execute();
// insert post and get its id
ResultSet rs = stmt.executeQuery();
// get the id of the new post
rs.next();
post.id = rs.getLong("id");
// check if there is a parent
if (post.parent.isPresent()) {
// create a new statement
stmt = c.prepareStatement("INSERT INTO comments(parent, child) VALUES (?, ?)");
// fill statement
stmt.setObject(1, post.parent.get());
stmt.setObject(2, post.id);
// execute statement
stmt.execute();
}
// commit the changes
c.commit();
// close all connections to db
stmt.close();
@@ -265,4 +289,43 @@ public class Routes {
return post;
}
@DeleteMapping("/post/{id}")
public void deletePost(@PathVariable long id) {
// DB connection and statement
Connection c = null;
PreparedStatement stmt = null;
// try to get data from db
try {
// check for the driver
Class.forName("org.postgresql.Driver");
// get the connection with credentials from env variables
c = DriverManager
.getConnection("jdbc:postgresql://"+
System.getenv("POSTGRES_IP")+"/"+System.getenv("POSTGRES_DB"),
System.getenv("POSTGRES_USER"), System.getenv("POSTGRES_PASSWORD"));
// disable auto commits
c.setAutoCommit(false);
// create a new statement
stmt = c.prepareStatement("UPDATE Posts SET deleted = now() WHERE id = ? AND deleted IS NULL");
stmt.setObject(1, id);
// insert delete time
stmt.execute();
// close all connections to db
stmt.close();
c.commit();
c.close();
}
// else log the error
catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Database is offline");
}
}
}