SqlX working

This commit is contained in:
Tyrel Souza 2022-10-17 12:16:46 -04:00
parent b5f71890a6
commit 8bf126279c
No known key found for this signature in database
GPG Key ID: F6582CF1308A2360
4 changed files with 24 additions and 13 deletions

View File

@ -2,7 +2,6 @@ package controllers
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"net/http"
"web-service-gin/internal/forms"
models2 "web-service-gin/internal/models"
@ -24,7 +23,7 @@ func NewAlbum(albumService models2.AlbumService) *Album {
// Post will create a new album from the given data, if the form is valid.
func (p *Album) Post(c *gin.Context) {
var form forms.CreateAlbum
if c.ShouldBindWith(&form, binding.JSON) != nil {
if c.ShouldBindJSON(&form) != nil {
// TODO: Give a better error message.
c.JSON(
http.StatusNotAcceptable,
@ -58,7 +57,7 @@ func (p *Album) Post(c *gin.Context) {
// Put will perform an update of a album.
func (p *Album) Put(c *gin.Context) {
var form forms.CreateAlbum
if err := c.ShouldBindWith(&form, binding.JSON); err != nil {
if err := c.ShouldBindJSON(&form); err != nil {
// TODO: Give a better error message.
c.JSON(
http.StatusNotAcceptable,

View File

@ -1,7 +1,7 @@
package forms
type CreateAlbum struct {
ID *int64 `form:"id" json:"id" binding:"required"`
ID *int64 `form:"id" json:"id"`
Title *string `form:"title" json:"title" binding:"required"`
Artist *string `form:"artist" json:"artist" binding:"required"`
Price *float64 `form:"price" json:"price" binding:"required"`

View File

@ -3,6 +3,7 @@ package sql
import (
"database/sql"
"github.com/jmoiron/sqlx"
"strconv"
"web-service-gin/internal/forms"
models2 "web-service-gin/internal/models"
)
@ -37,24 +38,28 @@ func NewAlbumService(conn *sqlx.DB) (*AlbumService, error) {
// Create will try to add the album to the DB.
func (s *AlbumService) Create(form *forms.CreateAlbum) (*models2.Album, error) {
q := `
INSERT INTO albums(title, artist, price)
VALUES (?, ?, ?)
RETURNING *;`
q := `INSERT INTO albums(title, artist, price) VALUES (?, ?, ?);`
var output models2.Album
err := s.conn.Get(
&output,
result, err := s.conn.Exec(
q,
*form.Title,
*form.Artist,
*form.Price,
)
if err != nil {
return nil, err
}
return &output, nil
id, err := result.LastInsertId()
if err != nil {
return nil, err
}
album, err := s.GetByID(strconv.FormatUint(uint64(id), 10))
if err != nil {
return nil, err
}
return album, nil
}
// Update will replace the values of the give album with those provided.

View File

@ -29,3 +29,10 @@ POST http://localhost:8080/albums
Content-Type: application/json
{"title": "Sarah Vaughan and Clifford Brown", "artist": "Sarah Vaughan", "price": 39.99}
###
POST http://localhost:8080/albums
Content-Type: application/json
{"title": "2Pacalypse", "artist": "2pac", "price": 75.23}