Allow empty note content, Delete note

This commit is contained in:
MrLetsplay 2023-08-26 22:11:43 +02:00
parent 836fab0d27
commit 4545c23fe6
Signed by: mr
SSH Key Fingerprint: SHA256:92jBH80vpXyaZHjaIl47pjRq+Yt7XGTArqQg1V7hSqg

40
main.go
View File

@ -100,11 +100,6 @@ func postNotes(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
return
}
if len(note.Content) == 0 {
writeError(w, http.StatusBadRequest, "Missing note content")
return
}
stmt, err := db.Prepare(`INSERT INTO Notes(Title, Content) VALUES(?, ?) RETURNING Id`)
if httpError(err, http.StatusInternalServerError, "Failed to store note", w) {
return
@ -186,11 +181,6 @@ func putNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
return
}
if len(note.Content) == 0 {
writeError(w, http.StatusBadRequest, "Missing note content")
return
}
stmt, err := db.Prepare(`UPDATE Notes SET Title = ?, Content = ? WHERE Id = ?`)
if httpError(err, http.StatusInternalServerError, "Failed to update note", w) {
return
@ -223,6 +213,35 @@ func putNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
w.Write(json)
}
func deleteNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if httpError(err, http.StatusBadRequest, "Invalid id", w) {
return
}
stmt, err := db.Prepare(`DELETE FROM Notes WHERE Id = ?`)
if httpError(err, http.StatusInternalServerError, "Failed to delete note", w) {
return
}
defer stmt.Close()
res, err := stmt.Exec(id)
if httpError(err, http.StatusInternalServerError, "Failed to delete note", w) {
return
}
deleted, err := res.RowsAffected()
if httpError(err, http.StatusInternalServerError, "Failed to delete note", w) {
return
}
if deleted == 0 {
writeError(w, http.StatusNotFound, "Note doesn't exist")
return
}
}
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
@ -302,6 +321,7 @@ func main() {
router.POST("/api/notes", postNotes)
router.GET("/api/notes/:id", getNote)
router.PUT("/api/notes/:id", putNote)
router.DELETE("/api/notes/:id", deleteNote)
http.ListenAndServe(":8080", router) // TODO: configure host, port, TLS
}