-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ReactJS CRUD completo consumindo Api Rest
- Loading branch information
Showing
17 changed files
with
579 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
Como rodar a Api. | ||
|
||
Pré Requisitos: | ||
|
||
Golang --> https://golang.org/dl/ | ||
|
||
MySQL --> https://dev.mysql.com/downloads/ | ||
|
||
|
||
Fazer o download dos seguinte pacotes: | ||
|
||
go get github.com/gorilla/mux | ||
|
||
go get github.com/gorilla/handlers | ||
|
||
go get github.com/jinzhu/gorm |
16 changes: 16 additions & 0 deletions
16
app-crud/api/go-api-products/api/controllers/HomeController.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package controllers | ||
|
||
import ( | ||
"net/http" | ||
"go-api-products/api/utils" | ||
) | ||
|
||
type ApiInfo struct { | ||
Name string `json:"name"` | ||
Version string `json:"version"` | ||
CreatedAt string `json:"created_at"` | ||
} | ||
|
||
func GetHome(w http.ResponseWriter, r *http.Request) { | ||
utils.ToJson(w, ApiInfo{"Api Crud Products", "1.0", "11 mar 2019 T20:02"}, http.StatusOK) | ||
} |
72 changes: 72 additions & 0 deletions
72
app-crud/api/go-api-products/api/controllers/ProductsController.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package controllers | ||
|
||
import ( | ||
"net/http" | ||
"encoding/json" | ||
"strconv" | ||
"go-api-products/api/utils" | ||
"go-api-products/api/models" | ||
"github.com/gorilla/mux" | ||
) | ||
|
||
func PostProduct(w http.ResponseWriter, r *http.Request) { | ||
body := utils.BodyParser(r) | ||
var product models.Product | ||
err := json.Unmarshal(body, &product) | ||
if err != nil { | ||
utils.ToJson(w, err.Error(), http.StatusUnprocessableEntity) | ||
return | ||
} | ||
rs, err := models.NewProduct(product) | ||
if err != nil { | ||
utils.ToJson(w, err.Error(), http.StatusUnprocessableEntity) | ||
return | ||
} | ||
utils.ToJson(w, rs, http.StatusCreated) | ||
} | ||
|
||
func GetProducts(w http.ResponseWriter, r *http.Request) { | ||
products := models.GetProducts() | ||
utils.ToJson(w, products, http.StatusOK) | ||
} | ||
|
||
func GetProduct(w http.ResponseWriter, r *http.Request) { | ||
vars := mux.Vars(r) | ||
id, _ := strconv.ParseUint(vars["id"], 10, 64) | ||
product := models.GetProductById(id) | ||
if product.Id == 0 { | ||
utils.ToJson(w, "Product not found", http.StatusBadRequest) | ||
return | ||
} | ||
utils.ToJson(w, product, http.StatusOK) | ||
} | ||
|
||
func PutProduct(w http.ResponseWriter, r *http.Request) { | ||
vars := mux.Vars(r) | ||
id, _ := strconv.ParseUint(vars["id"], 10, 64) | ||
body := utils.BodyParser(r) | ||
var product models.Product | ||
err := json.Unmarshal(body, &product) | ||
if err != nil { | ||
utils.ToJson(w, err.Error(), http.StatusUnprocessableEntity) | ||
return | ||
} | ||
product.Id = id | ||
rs, err := models.UpdateProduct(product) | ||
if err != nil { | ||
utils.ToJson(w, err.Error(), http.StatusUnprocessableEntity) | ||
return | ||
} | ||
utils.ToJson(w, rs, http.StatusOK) | ||
} | ||
|
||
func DeleteProduct(w http.ResponseWriter, r *http.Request) { | ||
vars := mux.Vars(r) | ||
id, _ := strconv.ParseUint(vars["id"], 10, 64) | ||
rows, err := models.DeleteProduct(id) | ||
if err != nil { | ||
utils.ToJson(w, err.Error(), http.StatusUnprocessableEntity) | ||
return | ||
} | ||
utils.ToJson(w, rows, http.StatusOK) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
package models | ||
|
||
import ( | ||
"log" | ||
"fmt" | ||
"github.com/jinzhu/gorm" | ||
_ "github.com/jinzhu/gorm/dialects/mysql" | ||
) | ||
|
||
const ( | ||
DB_USER = "root" | ||
DB_PASS = "@root" | ||
DB_HOST = "127.0.0.1" | ||
DB_PORT = 3306 | ||
DB_NAME = "mydb" | ||
) | ||
|
||
func Connect() *gorm.DB { | ||
URL := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", DB_USER, DB_PASS, DB_HOST, DB_PORT, DB_NAME) | ||
db, err := gorm.Open("mysql", URL) | ||
if err != nil { | ||
log.Fatal(err) | ||
return nil | ||
} | ||
return db | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package models | ||
|
||
import "time" | ||
|
||
type Product struct { | ||
Id uint64 `gorm:"primary_key;auto_increment" json:"id"` | ||
Description string `gorm:"size:255;not null" json:"description"` | ||
Price float32 `gorm:"type:decimal(10,2);not null" json:"price"` | ||
Quantity int `gorm:"default:0" json:"quantity"` | ||
Status string `gorm:"type:enum('0', '1');default:'1'" json:"status"` | ||
CreatedAt *time.Time `gorm:"default:current_timestamp()" json:"created_at"` | ||
UpdatedAt *time.Time `gorm:"default:current_timestamp()" json:"updated_at"` | ||
} | ||
|
||
func NewProduct(product Product) (interface{}, error) { | ||
db := Connect() | ||
defer db.Close() | ||
product.StatusVerify() | ||
rs := db.Create(&product) | ||
return rs.Value, rs.Error | ||
} | ||
|
||
func (p *Product) StatusVerify() string { | ||
if p.Quantity > 0 { | ||
p.Status = "1" | ||
} else { | ||
p.Status = "0" | ||
} | ||
return p.Status | ||
} | ||
|
||
func GetProducts() []Product { | ||
db := Connect() | ||
defer db.Close() | ||
var products []Product | ||
db.Order("id asc").Find(&products) | ||
return products | ||
} | ||
|
||
func GetProductById(id uint64) Product { | ||
db := Connect() | ||
defer db.Close() | ||
var product Product | ||
db.Where("id = ?", id).Find(&product) | ||
return product | ||
} | ||
|
||
func UpdateProduct(product Product) (interface{}, error) { | ||
db := Connect() | ||
defer db.Close() | ||
product.StatusVerify() | ||
rs := db.Model(&product).Where("id = ?", product.Id).UpdateColumns( | ||
map[string]interface{}{ | ||
"description": product.Description, | ||
"price": product.Price, | ||
"quantity": product.Quantity, | ||
"status": product.Status, | ||
"updated_at": time.Now(), | ||
}, | ||
) | ||
return rs.Value, rs.Error | ||
} | ||
|
||
func DeleteProduct(id uint64) (int64, error) { | ||
db := Connect() | ||
defer db.Close() | ||
rs := db.Where("id = ?", id).Delete(&Product{}) | ||
return rs.RowsAffected, rs.Error | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package routes | ||
|
||
import ( | ||
"net/http" | ||
"github.com/gorilla/mux" | ||
"github.com/gorilla/handlers" | ||
) | ||
|
||
func LoadCors(r *mux.Router) http.Handler { | ||
headers := handlers.AllowedHeaders([]string{"X-Request", "Content-Type", "Authorization"}) | ||
methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE"}) | ||
origins := handlers.AllowedOrigins([]string{"*"}) | ||
return handlers.CORS(headers, methods, origins)(r) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package routes | ||
|
||
import ( | ||
"go-api-products/api/controllers" | ||
"github.com/gorilla/mux" | ||
) | ||
|
||
func NewRouter() *mux.Router { | ||
r := mux.NewRouter().StrictSlash(true) | ||
r.HandleFunc("/", controllers.GetHome).Methods("GET") | ||
r.HandleFunc("/products", controllers.GetProducts).Methods("GET") | ||
r.HandleFunc("/products/{id}", controllers.GetProduct).Methods("GET") | ||
r.HandleFunc("/products", controllers.PostProduct).Methods("POST") | ||
r.HandleFunc("/products/{id}", controllers.PutProduct).Methods("PUT") | ||
r.HandleFunc("/products/{id}", controllers.DeleteProduct).Methods("DELETE") | ||
return r | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package api | ||
|
||
import ( | ||
"net/http" | ||
"fmt" | ||
"log" | ||
"go-api-products/api/routes" | ||
"go-api-products/api/models" | ||
) | ||
|
||
func Run() { | ||
|
||
db := models.Connect() | ||
db.DropTableIfExists(&models.Product{}) | ||
if !db.HasTable(&models.Product{}) { | ||
db.Debug().CreateTable(&models.Product{}) | ||
} | ||
db.Close() | ||
listen(9000) | ||
} | ||
|
||
func listen(p int) { | ||
port := fmt.Sprintf(":%d", p) | ||
fmt.Printf("\nListening Port %s...\n", port) | ||
r := routes.NewRouter() | ||
log.Fatal(http.ListenAndServe(port, routes.LoadCors(r))) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package utils | ||
|
||
import "log" | ||
|
||
func CheckErr(err error) { | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package utils | ||
|
||
import ( | ||
"net/http" | ||
"encoding/json" | ||
"io/ioutil" | ||
) | ||
|
||
func BodyParser(r *http.Request) []byte { | ||
body, _ := ioutil.ReadAll(r.Body) | ||
return body | ||
} | ||
|
||
func ToJson(w http.ResponseWriter, data interface{}, statusCode int) { | ||
w.Header().Set("Content-Type", "application/json") | ||
w.WriteHeader(statusCode) | ||
err := json.NewEncoder(w).Encode(data) | ||
CheckErr(err) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package main | ||
|
||
import ( | ||
"go-api-products/api" | ||
) | ||
|
||
func main() { | ||
api.Run() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
{ | ||
"name": "app-crud", | ||
"version": "0.1.0", | ||
"private": true, | ||
"dependencies": { | ||
"bootstrap": "^4.3.1", | ||
"pubsub-js": "^1.7.0", | ||
"react": "^16.8.4", | ||
"react-dom": "^16.8.4", | ||
"react-scripts": "2.1.8", | ||
"reactstrap": "^7.1.0" | ||
}, | ||
"scripts": { | ||
"start": "react-scripts start", | ||
"build": "react-scripts build", | ||
"test": "react-scripts test", | ||
"eject": "react-scripts eject" | ||
}, | ||
"eslintConfig": { | ||
"extends": "react-app" | ||
}, | ||
"browserslist": [ | ||
">0.2%", | ||
"not dead", | ||
"not ie <= 11", | ||
"not op_mini all" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import React, { Component } from 'react'; | ||
|
||
import Header from './components/Header'; | ||
|
||
import ProductBox from './components/Product'; | ||
|
||
class App extends Component { | ||
render() { | ||
return ( | ||
<div className="container"> | ||
<Header title="Products App" /> | ||
<br /> | ||
<ProductBox /> | ||
</div> | ||
); | ||
} | ||
} | ||
|
||
export default App; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import React from 'react'; | ||
|
||
import './styles.css'; | ||
|
||
const Header = ({ title }) => ( | ||
<header> | ||
<h1 className="font-weight-bold"> {title?title:'Escolha um Título'} </h1> | ||
</header> | ||
); | ||
|
||
export default Header; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
header { | ||
display: flex; | ||
height: 100px; | ||
align-items: center; | ||
justify-content: center; | ||
border-bottom: 1px solid #ccc; | ||
} |
Oops, something went wrong.