Add backups, currencies and dashboard APIs, and scope access by guard_name.
Web users may only CRUD their own records, operators stay in assigned branches, and admin/manager/superadmin keep full access. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
0d000f9af6
commit
28509eb4ca
65 files changed
+9132
-296
No files matched your search
@@ -0,0 +1,242 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/currency"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[currency.CurrencyDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) currency.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "currencies", currencyColumnsSQL, scanCurrency),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var currencyColumns = []string{
|
||||
"id", "currency_from", "currency_to", "value",
|
||||
"created_by", "updated_by", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
var currencyColumnsSQL = strings.Join(currencyColumns, ", ")
|
||||
|
||||
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', %s.first_name, %s.last_name)), ''), NULLIF(%s.name, ''), %s.username, '')`
|
||||
|
||||
const currencyFromClause = ` FROM currencies c
|
||||
LEFT JOIN users cu ON cu.id = c.created_by
|
||||
LEFT JOIN users uu ON uu.id = c.updated_by`
|
||||
|
||||
var currencySelectColumns = prefixed("c", currencyColumns) + `,
|
||||
` + fmt.Sprintf(userDisplaySQL, "cu", "cu", "cu", "cu") + `, COALESCE(cu.username, ''), COALESCE(cu.phone, ''), COALESCE(cu.email, ''),
|
||||
` + fmt.Sprintf(userDisplaySQL, "uu", "uu", "uu", "uu") + `, COALESCE(uu.username, ''), COALESCE(uu.phone, ''), COALESCE(uu.email, '')`
|
||||
|
||||
func prefixed(alias string, cols []string) string {
|
||||
parts := make([]string, len(cols))
|
||||
for i, col := range cols {
|
||||
parts[i] = alias + "." + col
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter currency.ListFilter) (currency.ListCurrencyDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM currencies c`+whereClause, args...).Scan(&count); err != nil {
|
||||
return currency.ListCurrencyDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY c.id DESC LIMIT $%d OFFSET $%d`,
|
||||
currencySelectColumns, currencyFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return currency.ListCurrencyDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []currency.CurrencyDTO
|
||||
for rows.Next() {
|
||||
item, err := scanCurrencyWithUsers(rows)
|
||||
if err != nil {
|
||||
return currency.ListCurrencyDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return currency.ListCurrencyDTO{}, err
|
||||
}
|
||||
|
||||
return currency.ListCurrencyDTO{Count: count, Currencies: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter currency.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Search != "" {
|
||||
args = append(args, likePattern(filter.Search))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
c.currency_from ILIKE $%[1]d ESCAPE '\' OR c.currency_to ILIKE $%[1]d ESCAPE '\'
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.CurrencyFrom != "" {
|
||||
args = append(args, filter.CurrencyFrom)
|
||||
conditions = append(conditions, fmt.Sprintf("c.currency_from = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CurrencyTo != "" {
|
||||
args = append(args, filter.CurrencyTo)
|
||||
conditions = append(conditions, fmt.Sprintf("c.currency_to = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (currency.CurrencyDTO, error) {
|
||||
query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1`
|
||||
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto currency.CreateCurrencyDTO) (currency.CurrencyDTO, error) {
|
||||
from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value)
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO currencies (currency_from, currency_to, value, created_by, updated_by)
|
||||
VALUES ($1, $2, $3::numeric, $4, $4)
|
||||
RETURNING ` + currencyColumnsSQL + `
|
||||
)
|
||||
SELECT ` + currencySelectColumns + `
|
||||
FROM inserted c
|
||||
LEFT JOIN users cu ON cu.id = c.created_by
|
||||
LEFT JOIN users uu ON uu.id = c.updated_by`
|
||||
|
||||
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.CreatedBy))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCurrencyDTO) (currency.CurrencyDTO, error) {
|
||||
from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value)
|
||||
query := `
|
||||
WITH updated AS (
|
||||
UPDATE currencies SET
|
||||
currency_from = $1, currency_to = $2, value = $3::numeric,
|
||||
updated_by = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
RETURNING ` + currencyColumnsSQL + `
|
||||
)
|
||||
SELECT ` + currencySelectColumns + `
|
||||
FROM updated c
|
||||
LEFT JOIN users cu ON cu.id = c.created_by
|
||||
LEFT JOIN users uu ON uu.id = c.updated_by`
|
||||
|
||||
item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.UpdatedBy, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return currency.CurrencyDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func normalizeRate(from, to string, value currency.RateValue) (string, string, string) {
|
||||
return strings.ToUpper(strings.TrimSpace(from)),
|
||||
strings.ToUpper(strings.TrimSpace(to)),
|
||||
strings.TrimSpace(value.String())
|
||||
}
|
||||
|
||||
func scanCurrency(row genericrepo.Scanner) (currency.CurrencyDTO, error) {
|
||||
return scanCurrencyRow(row, false)
|
||||
}
|
||||
|
||||
func scanCurrencyWithUsers(row genericrepo.Scanner) (currency.CurrencyDTO, error) {
|
||||
return scanCurrencyRow(row, true)
|
||||
}
|
||||
|
||||
func scanCurrencyRow(row genericrepo.Scanner, withUsers bool) (currency.CurrencyDTO, error) {
|
||||
var item currency.CurrencyDTO
|
||||
var value string
|
||||
dest := []interface{}{
|
||||
&item.Id, &item.CurrencyFrom, &item.CurrencyTo, &value,
|
||||
&item.CreatedById, &item.UpdatedById, &item.CreatedAt, &item.UpdatedAt,
|
||||
}
|
||||
|
||||
var createdName, createdUsername, createdPhone, createdEmail string
|
||||
var updatedName, updatedUsername, updatedPhone, updatedEmail string
|
||||
if withUsers {
|
||||
dest = append(dest,
|
||||
&createdName, &createdUsername, &createdPhone, &createdEmail,
|
||||
&updatedName, &updatedUsername, &updatedPhone, &updatedEmail,
|
||||
)
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return currency.CurrencyDTO{}, err
|
||||
}
|
||||
item.Value = currency.RateValue(trimNumeric(value))
|
||||
|
||||
if withUsers {
|
||||
item.CreatedBy = userInfo(item.CreatedById, createdName, createdUsername, createdPhone, createdEmail)
|
||||
item.UpdatedBy = userInfo(item.UpdatedById, updatedName, updatedUsername, updatedPhone, updatedEmail)
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func userInfo(id *int64, name, username, phone, email string) *currency.UserInfo {
|
||||
if id == nil {
|
||||
return nil
|
||||
}
|
||||
return ¤cy.UserInfo{
|
||||
Id: *id,
|
||||
Name: name,
|
||||
Username: username,
|
||||
Phone: phone,
|
||||
Email: email,
|
||||
}
|
||||
}
|
||||
|
||||
func trimNumeric(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if !strings.Contains(raw, ".") {
|
||||
return raw
|
||||
}
|
||||
raw = strings.TrimRight(raw, "0")
|
||||
raw = strings.TrimRight(raw, ".")
|
||||
if raw == "" {
|
||||
return "0"
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RateValue string
|
||||
|
||||
func (v RateValue) String() string { return string(v) }
|
||||
|
||||
func (v RateValue) MarshalJSON() ([]byte, error) {
|
||||
s := strings.TrimSpace(string(v))
|
||||
if s == "" {
|
||||
return []byte("0"), nil
|
||||
}
|
||||
return []byte(s), nil
|
||||
}
|
||||
|
||||
func (v *RateValue) UnmarshalJSON(b []byte) error {
|
||||
raw := strings.TrimSpace(string(b))
|
||||
if raw == "" || raw == "null" {
|
||||
*v = ""
|
||||
return nil
|
||||
}
|
||||
|
||||
var n json.Number
|
||||
if err := json.Unmarshal(b, &n); err == nil {
|
||||
*v = RateValue(n.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
*v = RateValue(strings.TrimSpace(s))
|
||||
return nil
|
||||
}
|
||||
|
||||
type CurrencyDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
CurrencyFrom string `json:"currencyFrom"`
|
||||
CurrencyTo string `json:"currencyTo"`
|
||||
Value RateValue `json:"value" swaggertype:"number"`
|
||||
CreatedById *int64 `json:"-"`
|
||||
CreatedBy *UserInfo `json:"createdBy,omitempty"`
|
||||
UpdatedById *int64 `json:"-"`
|
||||
UpdatedBy *UserInfo `json:"updatedBy,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type UserInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Username string `json:"username"`
|
||||
Phone string `json:"phone"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
type CreateCurrencyDTO struct {
|
||||
CurrencyFrom string `json:"currencyFrom" binding:"required"`
|
||||
CurrencyTo string `json:"currencyTo" binding:"required"`
|
||||
Value RateValue `json:"value" binding:"required" swaggertype:"number"`
|
||||
CreatedBy *int64 `json:"-"`
|
||||
}
|
||||
|
||||
type UpdateCurrencyDTO struct {
|
||||
CurrencyFrom string `json:"currencyFrom" binding:"required"`
|
||||
CurrencyTo string `json:"currencyTo" binding:"required"`
|
||||
Value RateValue `json:"value" binding:"required" swaggertype:"number"`
|
||||
UpdatedBy *int64 `json:"-"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Search string
|
||||
CurrencyFrom string
|
||||
CurrencyTo string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCurrencyDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Currencies []CurrencyDTO `json:"currencies"`
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/currencies"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List currency rates
|
||||
// @Description Returns paginated currency exchange rates
|
||||
// @Tags currencies
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param search query string false "Filter by currency code"
|
||||
// @Param currency_from query string false "Filter by source currency"
|
||||
// @Param currency_to query string false "Filter by target currency"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} ListCurrencyDTO
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list currencies failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get currency rate by ID
|
||||
// @Description Returns a single currency exchange rate
|
||||
// @Tags currencies
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Currency ID"
|
||||
// @Success 200 {object} CurrencyDTO
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get currency failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create currency rate
|
||||
// @Description Creates a new currency exchange rate
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateCurrencyDTO true "Currency rate payload"
|
||||
// @Success 201 {object} CurrencyDTO
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateCurrencyDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
dto.CreatedBy = currentUserID(c)
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create currency failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update currency rate
|
||||
// @Description Updates an existing currency exchange rate
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Currency ID"
|
||||
// @Param body body UpdateCurrencyDTO true "Currency rate payload"
|
||||
// @Success 200 {object} CurrencyDTO
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateCurrencyDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
dto.UpdatedBy = currentUserID(c)
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update currency failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete currency rate
|
||||
// @Description Deletes a currency exchange rate
|
||||
// @Tags currencies
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Currency ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete currency failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("currency removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{Page: defaultPage, Limit: defaultLimit}
|
||||
|
||||
if raw := queryValue(c, "page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := queryValue(c, "limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
if limit > maxLimit {
|
||||
limit = maxLimit
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
filter.Search = queryValue(c, "search", "q")
|
||||
filter.CurrencyFrom = strings.ToUpper(queryValue(c, "currency_from", "currencyFrom"))
|
||||
filter.CurrencyTo = strings.ToUpper(queryValue(c, "currency_to", "currencyTo"))
|
||||
return filter, true
|
||||
}
|
||||
|
||||
func queryValue(c *gin.Context, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) *int64 {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
if id > 0 {
|
||||
return &id
|
||||
}
|
||||
case int:
|
||||
if id > 0 {
|
||||
v := int64(id)
|
||||
return &v
|
||||
}
|
||||
case string:
|
||||
parsed, err := strconv.ParseInt(id, 10, 64)
|
||||
if err == nil && parsed > 0 {
|
||||
return &parsed
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package currency
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListCurrencyDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (CurrencyDTO, error)
|
||||
Create(ctx context.Context, dto CreateCurrencyDTO) (CurrencyDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateCurrencyDTO) (CurrencyDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
Reference in new issue
Block a user