Get post by ID, fix up update posts and add default values to null fields

This commit is contained in:
Amarpreet Minhas 2019-04-22 16:05:40 -04:00
parent 104edaf90a
commit ca6cace78d

View file

@ -94,6 +94,7 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
username := claims["username"].(string) username := claims["username"].(string)
err := json.NewDecoder(r.Body).Decode(newBlogPost) err := json.NewDecoder(r.Body).Decode(newBlogPost)
if err != nil { if err != nil {
returnError.Message = "unknown error, try again later"
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
@ -128,12 +129,12 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
return return
} }
} }
s := `INSERT INTO posts (title, slug, author, content, date) s := `INSERT INTO posts (title, slug, author, content, date, updated, update_time)
VALUES ($1, $2, $3, $4, $5) VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id` RETURNING id`
article_id := 0 article_id := 0
// write the row and get back the id // write the row and get back the id
err = DB.QueryRow(s, newBlogPost.Title, as, username, newBlogPost.Content, time.Now().UTC()).Scan(&article_id) err = DB.QueryRow(s, newBlogPost.Title, as, username, newBlogPost.Content, time.Now().UTC(), false, time.Now().UTC()).Scan(&article_id)
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
returnError.Message = "something is super broken..." returnError.Message = "something is super broken..."
@ -201,7 +202,6 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
// write the row update // write the row update
_ , err = DB.Exec(s, post.Title, post.Content, true, time.Now().UTC(), post.ID) _ , err = DB.Exec(s, post.Title, post.Content, true, time.Now().UTC(), post.ID)
if err != nil { if err != nil {
fmt.Println(err)
returnError.Message = "something is super broken..." returnError.Message = "something is super broken..."
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnError)
@ -218,6 +218,20 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
} }
func getBlogPostById(w http.ResponseWriter, r *http.Request) { func getBlogPostById(w http.ResponseWriter, r *http.Request) {
returnError := ReturnError{}
id := chi.URLParam(r, "id")
result := DB.QueryRow("SELECT id, title, slug, author, content, date, updated, update_time FROM posts WHERE id=$1", id)
post := BlogPost{}
err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.DatePublished, &post.Updated, &post.UpdateTime)
if err != nil {
fmt.Println(err)
returnError.Message = "post not found"
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
return
}
w.WriteHeader(http.StatusOK)
render.JSON(w, r, post)
return return
} }