Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new model with userId #20

Merged
merged 2 commits into from
Nov 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ CREATE DATABASE food_track;
```sql
create table meal (
id uuid primary key,
user_id varchar(255) not null,
name varchar(255) not null,
description varchar(255),
meal_type varchar(255) not null,
Expand Down
9 changes: 6 additions & 3 deletions controller/FoodConsumptionController.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func (s *FoodConsumptionController) FindAllConsumptionForMeal(c *gin.Context) {

func (s *FoodConsumptionController) AddFoodConsumption(c *gin.Context) {
mealId, err := uuid.Parse(c.Param("mealId"))
userId := c.GetHeader("iv-user")
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -51,7 +52,7 @@ func (s *FoodConsumptionController) AddFoodConsumption(c *gin.Context) {
})
return
}
foodConsumptionDto, err = s.foodConsumptionService.CreateFoodConsumptionForMeal(mealId, foodConsumptionDto)
foodConsumptionDto, err = s.foodConsumptionService.CreateFoodConsumptionForMeal(mealId, foodConsumptionDto, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -65,6 +66,7 @@ func (s *FoodConsumptionController) AddFoodConsumption(c *gin.Context) {

func (s *FoodConsumptionController) UpdateFoodConsumption(c *gin.Context) {
mealId, err := uuid.Parse(c.Param("mealId"))
userId := c.GetHeader("iv-user")
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -73,7 +75,7 @@ func (s *FoodConsumptionController) UpdateFoodConsumption(c *gin.Context) {
}
var foodConsumptionDto dto.FoodConsumptionDto
c.BindJSON(&foodConsumptionDto)
foodConsumptionDto, err = s.foodConsumptionService.UpdateFoodConsumptionForMeal(mealId, foodConsumptionDto)
foodConsumptionDto, err = s.foodConsumptionService.UpdateFoodConsumptionForMeal(mealId, foodConsumptionDto, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -88,13 +90,14 @@ func (s *FoodConsumptionController) UpdateFoodConsumption(c *gin.Context) {
func (s *FoodConsumptionController) DeleteFoodConsumption(c *gin.Context) {
mealId, err := uuid.Parse(c.Param("mealId"))
foodConsumptionId, err := uuid.Parse(c.Param("foodConsumptionId"))
userId := c.GetHeader("iv-user")
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
})
return
}
err = s.foodConsumptionService.DeleteFoodConsumptionForMeal(mealId, foodConsumptionId)
err = s.foodConsumptionService.DeleteFoodConsumptionForMeal(mealId, foodConsumptionId, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand Down
19 changes: 12 additions & 7 deletions controller/MealController.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ func (s *MealController) FindAllMeals(c *gin.Context) {
var mealDtos = make([]dto.MealDto, 0)
startRangeParam := c.Query("startRange")
endRangeParam := c.Query("endRange")
userId := c.GetHeader("iv-user")
if startRangeParam != "" && endRangeParam != "" {
startRange, err := time.Parse("02-01-2006", startRangeParam)
if err != nil {
Expand All @@ -32,7 +33,7 @@ func (s *MealController) FindAllMeals(c *gin.Context) {
if err != nil {
endRange = startRange
}
mealDtos, err = s.mealService.FindAllInDateRange(startRange, endRange)
mealDtos, err = s.mealService.FindAllInDateRange(startRange, endRange, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -41,7 +42,7 @@ func (s *MealController) FindAllMeals(c *gin.Context) {
}
} else {
var err error
mealDtos, err = s.mealService.FindAll()
mealDtos, err = s.mealService.FindAll(userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -58,7 +59,8 @@ func (s *MealController) FindAllMeals(c *gin.Context) {

func (s *MealController) FindMealById(c *gin.Context) {
id, _ := uuid.Parse(c.Param("mealId"))
mealDto, err := s.mealService.FindById(id)
userId := c.GetHeader("iv-user")
mealDto, err := s.mealService.FindById(id, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand Down Expand Up @@ -96,13 +98,14 @@ func (s *MealController) CreateMeal(c *gin.Context) {
func (s *MealController) UpdateMeal(c *gin.Context) {
var mealDto dto.MealDto
err := c.BindJSON(&mealDto)
userId := c.GetHeader("iv-user")
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
})
return
}
mealDto, err = s.mealService.Update(mealDto)
mealDto, err = s.mealService.Update(mealDto, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -117,7 +120,8 @@ func (s *MealController) UpdateMeal(c *gin.Context) {

func (s *MealController) DeleteMeal(c *gin.Context) {
id, _ := uuid.Parse(c.Param("mealId"))
err := s.mealService.Delete(id)
userId := c.GetHeader("iv-user")
err := s.mealService.Delete(id, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -134,6 +138,7 @@ func (s *MealController) GetMealStatistics(c *gin.Context) {
var mealStatisticsDto dto.MealStatisticsDto
startRangeParam := c.Query("startRange")
endRangeParam := c.Query("endRange")
userId := c.GetHeader("iv-user")
if startRangeParam != "" && endRangeParam != "" {
startRange, err := time.Parse("02-01-2006", startRangeParam)
if err != nil {
Expand All @@ -146,7 +151,7 @@ func (s *MealController) GetMealStatistics(c *gin.Context) {
if err != nil {
endRange = startRange
}
mealStatisticsDto, err = s.mealService.GetMealsStatistics(startRange, endRange)
mealStatisticsDto, err = s.mealService.GetMealsStatistics(startRange, endRange, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand All @@ -157,7 +162,7 @@ func (s *MealController) GetMealStatistics(c *gin.Context) {
startRange := time.Now().AddDate(0, 0, -7)
endRange := time.Now()
var err error
mealStatisticsDto, err = s.mealService.GetMealsStatistics(startRange, endRange)
mealStatisticsDto, err = s.mealService.GetMealsStatistics(startRange, endRange, userId)
if err != nil {
c.AbortWithStatusJSON(200, dto.BaseResponse[any]{
ErrorMessage: err.Error(),
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
module food-track-be

go 1.19
go 1.18

require (
github.com/gin-contrib/cors v1.4.0
github.com/gin-gonic/gin v1.8.1
github.com/google/uuid v1.3.0
github.com/mashingan/smapping v0.1.19
github.com/sony/gobreaker v0.5.0
github.com/uptrace/bun v1.1.8
github.com/uptrace/bun/dialect/pgdialect v1.1.8
github.com/uptrace/bun/driver/pgdriver v1.1.8
)

require (
github.com/gin-contrib/cors v1.4.0 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
Expand All @@ -25,7 +26,6 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/sony/gobreaker v0.5.0 // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect
Expand Down
21 changes: 17 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
"log"
"net/http"
"os"
"time"
Expand All @@ -27,12 +26,23 @@ func main() {
pgdriver.WithUser(os.Getenv("DB_USER")),
pgdriver.WithPassword(os.Getenv("DB_PASSWORD")),
pgdriver.WithDatabase(os.Getenv("DB_NAME")),
pgdriver.WithInsecure(true),
pgdriver.WithTimeout(5*time.Second),
)
sqldb := sql.OpenDB(pgconn)

db := bun.NewDB(sqldb, pgdialect.New())
log.Println(db.Ping())

defer func(db *bun.DB) {
err := db.Close()
if err != nil {
panic(err)
}
}(db)

err := db.Ping()
if err != nil {
panic(err)
}

mr := repository.NewMealRepository(*db)
fcr := repository.NewFoodConsumptionRepository(*db)
Expand All @@ -43,7 +53,10 @@ func main() {
fcc := controller.NewFoodConsumptionController(fcs)

r := gin.Default()
r.Use(cors.Default())
corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
corsConfig.AllowHeaders = append(corsConfig.AllowHeaders, "iv-user")
r.Use(cors.New(corsConfig))

r.GET("/meal", mc.FindAllMeals)
r.GET("/meal/:mealId", mc.FindMealById)
Expand Down
2 changes: 2 additions & 0 deletions model/Meal.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
type Meal struct {
bun.BaseModel `bun:"table:meal,alias:m"`
ID uuid.UUID `bun:"type:uuid,nullzero,pk"`
UserId string `bun:"type:varchar(255),notnull"`
Name string `bun:"type:varchar(255),notnull"`
Description string `bun:"type:varchar(255),nullzero"`
MealType MealType `bun:"type:varchar(255),notnull"`
Expand Down Expand Up @@ -40,6 +41,7 @@ const (
DDL for table meal
create table meal (
id uuid primary key,
user_id varchar(255) not null,
name varchar(255) not null,
description varchar(255),
meal_type varchar(255) not null,
Expand Down
1 change: 1 addition & 0 deletions model/dto/MealDto.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

type MealDto struct {
ID uuid.UUID `json:"id,omitempty"`
UserId string `json:"userId,omitempty"`
Name string `json:"name"`
Description string `json:"description"`
MealType model.MealType `json:"mealType"`
Expand Down
44 changes: 22 additions & 22 deletions repository/MealRepository.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,34 @@ func NewMealRepository(db bun.DB) *MealRepository {
return &MealRepository{db: db, ctx: context.Background()}
}

func (r *MealRepository) FindAll() ([]*model.Meal, error) {
func (r *MealRepository) FindAll(userId string) ([]*model.Meal, error) {
var meals []*model.Meal
err := r.db.NewSelect().Model(&meals).Scan(r.ctx)
err := r.db.NewSelect().Model(&meals).Where("user_id = ?", userId).Scan(r.ctx)
return meals, err
}

func (r *MealRepository) FindById(id uuid.UUID) (*model.Meal, error) {
func (r *MealRepository) FindByIdAndUserId(id uuid.UUID, userId string) (*model.Meal, error) {
var meal model.Meal
err := r.db.NewSelect().Model(&meal).Where("id = ?", id).Scan(r.ctx)
err := r.db.NewSelect().Model(&meal).Where("id = ?", id).Where("user_id = ?", userId).Scan(r.ctx)
return &meal, err
}

func (r *MealRepository) Create(meal *model.Meal) (sql.Result, error) {
return r.db.NewInsert().Model(meal).Exec(r.ctx)
}

func (r *MealRepository) Update(meal *model.Meal) (sql.Result, error) {
return r.db.NewUpdate().Model(meal).Where("id = ?", meal.ID).Exec(r.ctx)
func (r *MealRepository) Update(meal *model.Meal, userId string) (sql.Result, error) {
return r.db.NewUpdate().Model(meal).Where("id = ?", meal.ID).Where("user_id = ?", userId).Exec(r.ctx)
}

func (r *MealRepository) Delete(meal *model.Meal) (sql.Result, error) {
return r.db.NewDelete().Model(meal).Where("id = ?", meal.ID).Exec(r.ctx)
func (r *MealRepository) Delete(meal *model.Meal, userId string) (sql.Result, error) {
return r.db.NewDelete().Model(meal).Where("id = ? ", meal.ID, userId).Where("user_id = ?", userId).Exec(r.ctx)
}

func (r *MealRepository) GetAverageKcalEatenInDateRange(startRange time.Time, endRange time.Time) (float64, error) {
func (r *MealRepository) GetAverageKcalEatenInDateRange(startRange time.Time, endRange time.Time, userId string) (float64, error) {
var result float64
queryStr := "SELECT SUM(COALESCE(kcal, 0)) FROM food_consumption WHERE meal_id IN (SELECT id FROM meal WHERE date BETWEEN ? AND ?)"
queryResult, err := r.db.Query(queryStr, startRange, endRange)
queryStr := "SELECT SUM(COALESCE(kcal, 0)) FROM food_consumption WHERE meal_id IN (SELECT id FROM meal WHERE user_id = ? AND date BETWEEN ? AND ?)"
queryResult, err := r.db.Query(queryStr, userId, startRange, endRange)
if err != nil {
return 0, err
}
Expand All @@ -62,16 +62,16 @@ func (r *MealRepository) GetAverageKcalEatenInDateRange(startRange time.Time, en
return result / rangeInDays, nil
}

func (r *MealRepository) GetAverageKcalEatenInDateRangePerMealType(startRange time.Time, endRange time.Time) ([]dto.AvgKcalPerMealTypeDto, error) {
func (r *MealRepository) GetAverageKcalEatenInDateRangePerMealType(startRange time.Time, endRange time.Time, userId string) ([]dto.AvgKcalPerMealTypeDto, error) {
var result = make([]dto.AvgKcalPerMealTypeDto, 0)
var rangeInDays float64
if startRange.Equal(endRange) {
rangeInDays = 1
} else {
rangeInDays = endRange.Sub(startRange).Hours() / 24
}
queryStr := "SELECT m.meal_type, SUM(COALESCE(kcal, 0)) / ? as avg_kcal FROM meal m join food_consumption fc on m.id = fc.meal_id WHERE date BETWEEN ? AND ? group by m.meal_type"
queryResult, err := r.db.Query(queryStr, rangeInDays, startRange, endRange)
queryStr := "SELECT m.meal_type, SUM(COALESCE(kcal, 0)) / ? as avg_kcal FROM meal m join food_consumption fc on m.id = fc.meal_id WHERE m.user_id = ? AND date BETWEEN ? AND ? group by m.meal_type"
queryResult, err := r.db.Query(queryStr, rangeInDays, userId, startRange, endRange)
if err != nil {
return []dto.AvgKcalPerMealTypeDto{}, err
}
Expand All @@ -89,10 +89,10 @@ func (r *MealRepository) GetAverageKcalEatenInDateRangePerMealType(startRange ti
return result, nil
}

func (r *MealRepository) GetAverageFoodCostInDateRange(startRange time.Time, endRange time.Time) (float64, error) {
func (r *MealRepository) GetAverageFoodCostInDateRange(startRange time.Time, endRange time.Time, userId string) (float64, error) {
var result float64
queryStr := "SELECT SUM(COALESCE(cost, 0)) FROM food_consumption WHERE meal_id IN (SELECT id FROM meal WHERE date BETWEEN ? AND ?)"
queryResult, err := r.db.Query(queryStr, startRange, endRange)
queryStr := "SELECT SUM(COALESCE(cost, 0)) FROM food_consumption WHERE meal_id IN (SELECT id FROM meal WHERE user_id = ? AND date BETWEEN ? AND ?)"
queryResult, err := r.db.Query(queryStr, userId, startRange, endRange)
if err != nil {
return 0, err
}
Expand All @@ -108,10 +108,10 @@ func (r *MealRepository) GetAverageFoodCostInDateRange(startRange time.Time, end
return result / rangeInDays, nil
}

func (r *MealRepository) GetSumFoodCostInDateRange(startRange time.Time, endRange time.Time) (float64, error) {
func (r *MealRepository) GetSumFoodCostInDateRange(startRange time.Time, endRange time.Time, userId string) (float64, error) {
var result float64
queryStr := "SELECT SUM(COALESCE(cost, 0)) FROM food_consumption WHERE meal_id IN (SELECT id FROM meal WHERE date BETWEEN ? AND ?)"
queryResult, err := r.db.Query(queryStr, startRange, endRange)
queryStr := "SELECT SUM(COALESCE(cost, 0)) FROM food_consumption WHERE meal_id IN (SELECT id FROM meal WHERE user_id = ? AND date BETWEEN ? AND ?)"
queryResult, err := r.db.Query(queryStr, userId, startRange, endRange)
if err != nil {
return 0, err
}
Expand All @@ -123,9 +123,9 @@ func (r *MealRepository) GetSumFoodCostInDateRange(startRange time.Time, endRang
return result, nil
}

func (r *MealRepository) GetMealInDateRange(startRange time.Time, endRange time.Time) ([]model.Meal, error) {
func (r *MealRepository) GetMealInDateRange(startRange time.Time, endRange time.Time, userId string) ([]model.Meal, error) {
var meals []model.Meal
err := r.db.NewSelect().Model(&meals).Where("date BETWEEN ? AND ?", startRange, endRange).Scan(r.ctx)
err := r.db.NewSelect().Model(&meals).Where("date BETWEEN ? AND ?", startRange, endRange).Where("user_id = ?", userId).Scan(r.ctx)
if err != nil {
return []model.Meal{}, err
}
Expand Down
Loading