Skatepark Code
Some code for how the backend of the skatepark posts API works, and other problems
How I started
- Copied the jokes API
- Added some more columns for information about the post
public class Skatepark {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = false)
private String skateparkName;
private String author;
private String title;
private String address;
private double starRating;
private String description;
private int totalLikes;
public Skatepark(String skateparkName, String author, String title, String address, double starRating, String description, int totalLikes) {
this.skateparkName = skateparkName;
this.author = author;
this.title = title;
this.address = address;
this.starRating = starRating;
this.description = description;
this.totalLikes = totalLikes;
}
// Setters and Getters
}
My plan for the controller
- Have a create method
- Update Like method
- Delete method
- Read should be easy
@GetMapping("/")
public ResponseEntity<List<Skatepark>> getSkateparks() {
return new ResponseEntity<>(repository.findAll(), HttpStatus.OK);
}
@PostMapping("/create")
public ResponseEntity<Skatepark> createSkatepark(@RequestBody Skatepark skatepark) {
Skatepark savedSkatepark = repository.save(skatepark);
return new ResponseEntity<>(savedSkatepark, HttpStatus.CREATED);
}
@PostMapping("/like/{name}") // Change the path variable to 'name'
public ResponseEntity<Skatepark> updateLikes(@PathVariable String name) {
List<Skatepark> skateparks = repository.findBySkateparkName(name);
if (!skateparks.isEmpty()) {
Skatepark skatepark = skateparks.get(0); // Assuming you want to work with the first matching skatepark
int currentLikes = skatepark.getTotalLikes();
skatepark.setTotalLikes(currentLikes + 1); // Increment likes by 1
// You can also update the author who liked the skatepark
repository.save(skatepark);
return new ResponseEntity<>(skatepark, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@DeleteMapping("/delete/{name}")
public ResponseEntity<Void> deleteSkatepark(@PathVariable String name) {
List<Skatepark> skateparks = repository.findBySkateparkName(name);
if (!skateparks.isEmpty()) {
repository.delete(skateparks.get(0)); // Assuming you want to delete the first matching skatepark
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}