Skip to content

Commit

Permalink
Added photos to trips (#47)
Browse files Browse the repository at this point in the history
* added grpc to delivery for trips

* microservices added

* changed main

* attractions service fixed

* userService

* gRPC for users

* fixing

* added auth routes

* services fixed

* returned token in cookie

* fixed login and search

* scheme changed

* made structure for survey's microservice

* fixed names

* added image path to searh response

* fix

* fixed getPlace

* proto added

* http handler for surveys

* made http handlers for surveys

* grpc server added

* started repo

* started usecase for surveys

* finished repo

* made usecase for surveys

* grpc server added

* SCHEME BD CHANGE

* SCHEME BD CHANGE

* SCHEME BD CHANGE

* fixed mistakes with error handling

* ne znay

* ne znay

* ne znay

* ne znay

* fixed authorization

* fixed trip queries

* added field description to db

* added global search to microservices

* added photos to trips

* fixed deleting review

* fixed trip queries

* temporary loggig

* fixed base64 decoding

* saving only file_name

* fixed review route

* fixed routing

* added photo deletion

* deleted temporary logging

* minor fix

* temporary logging

* deleted temporary logging

* made logging

---------

Co-authored-by: timurIsaevIY <isaevtimur2016@gmail.com>
Co-authored-by: AnnHarvard <dana.shakleina@yandex.ru>
  • Loading branch information
3 people authored Nov 27, 2024
1 parent 4539932 commit bdfb3cc
Show file tree
Hide file tree
Showing 17 changed files with 261 additions and 65 deletions.
13 changes: 8 additions & 5 deletions cmd/attractions/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
genCities "2024_2_ThereWillBeName/internal/pkg/cities/delivery/grpc/gen"
citiesRepo "2024_2_ThereWillBeName/internal/pkg/cities/repo"
citiesUsecase "2024_2_ThereWillBeName/internal/pkg/cities/usecase"
"2024_2_ThereWillBeName/internal/pkg/dblogger"
"2024_2_ThereWillBeName/internal/pkg/logger"
grpcReviews "2024_2_ThereWillBeName/internal/pkg/reviews/delivery/grpc"
genReviews "2024_2_ThereWillBeName/internal/pkg/reviews/delivery/grpc/gen"
Expand Down Expand Up @@ -52,15 +53,17 @@ func main() {
}
defer db.Close()

reviewsRepo := reviewRepo.NewReviewRepository(db)
wrappedDB := dblogger.NewDB(db, logger)

reviewsRepo := reviewRepo.NewReviewRepository(wrappedDB)
reviewUsecase := reviewUsecase.NewReviewsUsecase(reviewsRepo)
placeRepo := placeRepo.NewPLaceRepository(db)
placeRepo := placeRepo.NewPLaceRepository(wrappedDB)
placeUsecase := placeUsecase.NewPlaceUsecase(placeRepo)
citiesRepo := citiesRepo.NewCitiesRepository(db)
citiesRepo := citiesRepo.NewCitiesRepository(wrappedDB)
citiesUsecase := citiesUsecase.NewCitiesUsecase(citiesRepo)
categoriesRepo := categoriesRepo.NewCategoriesRepo(db)
categoriesRepo := categoriesRepo.NewCategoriesRepo(wrappedDB)
categoriesUsecase := categoriesUsecase.NewCategoriesUsecase(categoriesRepo)
searchRepo := searchRepo.NewSearchRepository(db)
searchRepo := searchRepo.NewSearchRepository(wrappedDB)
searchUsecase := searchUsecase.NewSearchUsecase(searchRepo)

grpcAttractionsServer := grpc.NewServer()
Expand Down
2 changes: 2 additions & 0 deletions cmd/gateway/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ func main() {
r := mux.NewRouter().PathPrefix("/api/v1").Subrouter()
r.Use(corsMiddleware.CorsMiddleware)

r.Use(middleware.RequestLoggerMiddleware(logger))

// Обработка ненайденных маршрутов
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response := httpresponses.ErrorResponse{
Expand Down
8 changes: 6 additions & 2 deletions cmd/trips/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"2024_2_ThereWillBeName/internal/models"
"2024_2_ThereWillBeName/internal/pkg/dblogger"
"2024_2_ThereWillBeName/internal/pkg/logger"
grpcTrips "2024_2_ThereWillBeName/internal/pkg/trips/delivery/grpc"
"2024_2_ThereWillBeName/internal/pkg/trips/delivery/grpc/gen"
Expand All @@ -10,7 +11,6 @@ import (
"database/sql"
"flag"
"fmt"
_ "github.com/lib/pq"
"log"
"log/slog"
"net"
Expand All @@ -19,6 +19,8 @@ import (
"strconv"
"syscall"

_ "github.com/lib/pq"

"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
Expand All @@ -37,7 +39,9 @@ func main() {
}
defer db.Close()

tripRepo := tripRepo.NewTripRepository(db)
wrappedDB := dblogger.NewDB(db, logger)

tripRepo := tripRepo.NewTripRepository(wrappedDB)
tripUsecase := tripUsecase.NewTripsUsecase(tripRepo)

grpcTripsServer := grpc.NewServer()
Expand Down
8 changes: 6 additions & 2 deletions cmd/users/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"2024_2_ThereWillBeName/internal/models"
"2024_2_ThereWillBeName/internal/pkg/dblogger"
"2024_2_ThereWillBeName/internal/pkg/logger"
grpcUsers "2024_2_ThereWillBeName/internal/pkg/user/delivery/grpc"
"2024_2_ThereWillBeName/internal/pkg/user/delivery/grpc/gen"
Expand All @@ -10,7 +11,6 @@ import (
"database/sql"
"flag"
"fmt"
_ "github.com/lib/pq"
"log"
"log/slog"
"net"
Expand All @@ -19,6 +19,8 @@ import (
"strconv"
"syscall"

_ "github.com/lib/pq"

"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
Expand All @@ -39,7 +41,9 @@ func main() {
}
defer db.Close()

userRepo := userRepo.NewAuthRepository(db)
wrappedDB := dblogger.NewDB(db, logger)

userRepo := userRepo.NewAuthRepository(wrappedDB)
userUsecase := userUsecase.NewUserUsecase(userRepo, storagePath)

grpcUsersServer := grpc.NewServer()
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ require (
require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
Expand Down
5 changes: 3 additions & 2 deletions internal/pkg/attractions/repo/place_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package repo

import (
"2024_2_ThereWillBeName/internal/models"
"2024_2_ThereWillBeName/internal/pkg/dblogger"
"context"
"database/sql"
_ "embed"
Expand All @@ -12,10 +13,10 @@ import (
)

type PlaceRepository struct {
db *sql.DB
db *dblogger.DB
}

func NewPLaceRepository(db *sql.DB) *PlaceRepository {
func NewPLaceRepository(db *dblogger.DB) *PlaceRepository {
return &PlaceRepository{db: db}
}

Expand Down
6 changes: 3 additions & 3 deletions internal/pkg/categories/repo/categories_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ package repo

import (
"2024_2_ThereWillBeName/internal/models"
"2024_2_ThereWillBeName/internal/pkg/dblogger"
"context"
"database/sql"
"fmt"
)

type CategoriesRepo struct {
db *sql.DB
db *dblogger.DB
}

func NewCategoriesRepo(db *sql.DB) *CategoriesRepo {
func NewCategoriesRepo(db *dblogger.DB) *CategoriesRepo {
return &CategoriesRepo{db: db}
}

Expand Down
5 changes: 3 additions & 2 deletions internal/pkg/cities/repo/cities_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package repo

import (
"2024_2_ThereWillBeName/internal/models"
"2024_2_ThereWillBeName/internal/pkg/dblogger"

"context"
"database/sql"
Expand All @@ -10,10 +11,10 @@ import (
)

type CitiesRepository struct {
db *sql.DB
db *dblogger.DB
}

func NewCitiesRepository(db *sql.DB) *CitiesRepository {
func NewCitiesRepository(db *dblogger.DB) *CitiesRepository {
return &CitiesRepository{db: db}
}

Expand Down
89 changes: 89 additions & 0 deletions internal/pkg/dblogger/dblogger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package dblogger

import (
"context"
"database/sql"
"log/slog"
"time"
)

type DB struct {
db *sql.DB
logger *slog.Logger
}

func NewDB(db *sql.DB, logger *slog.Logger) *DB {
return &DB{
db: db,
logger: logger,
}
}

func (d *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
start := time.Now()
rows, err := d.db.QueryContext(ctx, query, args...)
duration := time.Since(start)

d.logger.DebugContext(ctx, "Executing QueryContext",
slog.String("query", query),
slog.Any("args", args),
slog.Duration("duration", duration),
slog.String("error", errToString(err)),
)

return rows, err
}

func (d *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
start := time.Now()
result, err := d.db.ExecContext(ctx, query, args...)
duration := time.Since(start)

d.logger.DebugContext(ctx, "Executing ExecContext",
slog.String("query", query),
slog.Any("args", args),
slog.Duration("duration", duration),
slog.String("error", errToString(err)),
)

return result, err
}

func (d *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
start := time.Now()
row := d.db.QueryRowContext(ctx, query, args...)
duration := time.Since(start)

d.logger.DebugContext(ctx, "Executing QueryRowContext",
slog.String("query", query),
slog.Any("args", args),
slog.Duration("duration", duration),
)

return row
}

func (d *DB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
start := time.Now()
stmt, err := d.db.PrepareContext(ctx, query)
duration := time.Since(start)

d.logger.DebugContext(ctx, "Preparing statement",
slog.String("query", query),
slog.Duration("duration", duration),
slog.String("error", errToString(err)),
)

return stmt, err
}

func (d *DB) Close() error {
return d.db.Close()
}

func errToString(err error) string {
if err != nil {
return err.Error()
}
return "nil"
}
62 changes: 62 additions & 0 deletions internal/pkg/middleware/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package middleware

import (
log "2024_2_ThereWillBeName/internal/pkg/logger"
"log/slog"
"net/http"
"time"

"github.com/google/uuid"
)

const (
RequestIDKey contextKey = "request_id"
MethodKey contextKey = "method"
PathKey contextKey = "path"
)

type responseWriter struct {
http.ResponseWriter
statusCode int
}

func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}

func RequestLoggerMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := uuid.New().String()

logCtx := r.Context()
logCtx = log.AppendCtx(logCtx, slog.String("request_id", requestID))
logCtx = log.AppendCtx(logCtx, slog.String("method", r.Method))
logCtx = log.AppendCtx(logCtx, slog.String("path", r.URL.Path))
r = r.WithContext(logCtx)

startTime := time.Now()
logger.Info("Request started",
slog.String("request_id", requestID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Time("start_time", startTime),
)

rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}

next.ServeHTTP(rw, r)

duration := time.Since(startTime)

logger.Info("Request completed",
slog.String("request_id", requestID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status_code", rw.statusCode),
slog.Duration("duration", duration),
)
})
}
}
6 changes: 5 additions & 1 deletion internal/pkg/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package middleware
import (
httpresponse "2024_2_ThereWillBeName/internal/pkg/httpresponses"
"2024_2_ThereWillBeName/internal/pkg/jwt"
log "2024_2_ThereWillBeName/internal/pkg/logger"
"context"
"log/slog"
"net/http"
"strconv"
)

type contextKey string
Expand Down Expand Up @@ -46,11 +48,13 @@ func MiddlewareAuth(jwtService jwt.JWTInterface, next http.Handler, logger *slog
login := claims["login"].(string)
email := claims["email"].(string)
if logger != nil {
logger.Info("Token parsed", slog.Int("userID", int(userID)), slog.String("login", login), slog.String("email", email))
logger.Debug("Token parsed", slog.Int("userID", int(userID)), slog.String("login", login), slog.String("email", email))
}
ctx := context.WithValue(r.Context(), IdKey, userID)
ctx = context.WithValue(ctx, LoginKey, login)
ctx = context.WithValue(ctx, EmailKey, email)
ctx = log.AppendCtx(ctx, slog.String("user_id", strconv.FormatUint(uint64(userID), 10)))

r = r.WithContext(ctx)

next.ServeHTTP(w, r)
Expand Down
Loading

0 comments on commit bdfb3cc

Please sign in to comment.