Localize client API responses by lang query param.

Client endpoints now return a single-language string (default tm) so the frontend can pass ?lang= and skip picking from nested tm/ru/en objects.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-06 12:27:10 +05:00
parent 76848f4982
commit ddd898078c
5 changed files with 202 additions and 110 deletions

View File

@@ -22,9 +22,10 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) users.Repos
} }
} }
func (r repository) GetNews(ctx context.Context, limit, page int) (users.DataNewsDTO, error) { func (r repository) GetNews(ctx context.Context, limit, page int, lang string) (users.DataNewsDTO, error) {
var dt users.DataNewsDTO var dt users.DataNewsDTO
lang = users.NormalizeLang(lang)
// List endpoint: skip news_content (large HTML). Full body is loaded via GetNewsById. // List endpoint: skip news_content (large HTML). Full body is loaded via GetNewsById.
// Default to latest 6 when limit/page not provided. // Default to latest 6 when limit/page not provided.
@@ -51,11 +52,13 @@ func (r repository) GetNews(ctx context.Context, limit, page int) (users.DataNew
ns := []users.NewsDTO{} ns := []users.NewsDTO{}
for rows.Next() { for rows.Next() {
var n users.NewsDTO var n users.NewsDTO
errN := rows.Scan(&n.Id, &n.Title, &n.Image) var title users.Language
errN := rows.Scan(&n.Id, &title, &n.Image)
if errN != nil { if errN != nil {
r.logger.Error("errN :::", errN) r.logger.Error("errN :::", errN)
continue continue
} }
n.Title = title.Pick(lang)
ns = append(ns, n) ns = append(ns, n)
} }
@@ -64,16 +67,17 @@ func (r repository) GetNews(ctx context.Context, limit, page int) (users.DataNew
return dt, nil return dt, nil
} }
func (r repository) GetCategories(ctx context.Context) ([]users.CategoryDTO, error) { func (r repository) GetCategories(ctx context.Context, lang string) ([]users.CategoryDTO, error) {
lang = users.NormalizeLang(lang)
// Menu only needs id/name; page content is loaded via GetSubCategoryById. // Menu only needs id/name; page content is loaded via GetSubCategoryById.
q := ` SELECT q := ` SELECT
c.id, c.name, c.id, COALESCE(c.name->>$1, ''),
COALESCE( COALESCE(
jsonb_agg( jsonb_agg(
jsonb_build_object( jsonb_build_object(
'id', sc.id, 'categoryId', sc.category_id, 'id', sc.id, 'categoryId', sc.category_id,
'name', sc.name 'name', COALESCE(sc.name->>$1, '')
) )
ORDER BY sc.created_at ASC ORDER BY sc.created_at ASC
) FILTER (WHERE sc.id IS NOT NULL), ) FILTER (WHERE sc.id IS NOT NULL),
@@ -85,7 +89,7 @@ func (r repository) GetCategories(ctx context.Context) ([]users.CategoryDTO, err
GROUP BY c.id GROUP BY c.id
ORDER BY c.created_at DESC;` ORDER BY c.created_at DESC;`
rows, err := r.client.Query(ctx, q) rows, err := r.client.Query(ctx, q, lang)
if err != nil { if err != nil {
r.logger.Error("get categories :::", err) r.logger.Error("get categories :::", err)
return nil, err return nil, err
@@ -153,8 +157,12 @@ func (r repository) GetBanners(ctx context.Context, limit, page int) (users.Data
return dt, nil return dt, nil
} }
func (r repository) GetBannerById(ctx context.Context, id int) (users.BannerDTO, error) { func (r repository) GetBannerById(ctx context.Context, id int, lang string) (users.BannerDTO, error) {
var b users.BannerDTO var b users.BannerDTO
lang = users.NormalizeLang(lang)
var title users.Language
var contentTm, contentRu, contentEn string
q := ` SELECT q := ` SELECT
id, title, id, title,
@@ -164,19 +172,22 @@ func (r repository) GetBannerById(ctx context.Context, id int) (users.BannerDTO,
WHERE id = $1;` WHERE id = $1;`
err := r.client.QueryRow(ctx, q, id).Scan( err := r.client.QueryRow(ctx, q, id).Scan(
&b.Id, &b.Title, &b.Id, &title,
&b.ContentTm, &b.ContentRu, &b.ContentEn, &contentTm, &contentRu, &contentEn,
&b.Image, &b.CreatedAt, &b.Image, &b.CreatedAt,
) )
if err != nil { if err != nil {
return b, err return b, err
} }
b.Title = title.Pick(lang)
b.Content = users.PickContent(lang, contentTm, contentRu, contentEn)
return b, nil return b, nil
} }
func (r repository) GetStatics(ctx context.Context, limit, page int) (users.DataStaticDTO, error) { func (r repository) GetStatics(ctx context.Context, limit, page int, lang string) (users.DataStaticDTO, error) {
var dt users.DataStaticDTO var dt users.DataStaticDTO
lang = users.NormalizeLang(lang)
// Grid only needs id/logo/title. Full body is loaded via GetStaticById. // Grid only needs id/logo/title. Full body is loaded via GetStaticById.
q := ` SELECT q := ` SELECT
@@ -204,11 +215,13 @@ func (r repository) GetStatics(ctx context.Context, limit, page int) (users.Data
ss := []users.StaticDTO{} ss := []users.StaticDTO{}
for rows.Next() { for rows.Next() {
var s users.StaticDTO var s users.StaticDTO
errS := rows.Scan(&s.Id, &s.Logo, &s.Title) var title users.Language
errS := rows.Scan(&s.Id, &s.Logo, &title)
if errS != nil { if errS != nil {
r.logger.Error("errS :::", errS) r.logger.Error("errS :::", errS)
continue continue
} }
s.Title = title.Pick(lang)
ss = append(ss, s) ss = append(ss, s)
} }
@@ -217,8 +230,12 @@ func (r repository) GetStatics(ctx context.Context, limit, page int) (users.Data
return dt, nil return dt, nil
} }
func (r repository) GetStaticById(ctx context.Context, id int) (users.StaticDTO, error) { func (r repository) GetStaticById(ctx context.Context, id int, lang string) (users.StaticDTO, error) {
var s users.StaticDTO var s users.StaticDTO
lang = users.NormalizeLang(lang)
var title users.Language
var contentTm, contentRu, contentEn string
q := ` SELECT q := ` SELECT
id, logo, title, id, logo, title,
@@ -228,18 +245,24 @@ func (r repository) GetStaticById(ctx context.Context, id int) (users.StaticDTO,
WHERE id = $1;` WHERE id = $1;`
err := r.client.QueryRow(ctx, q, id).Scan( err := r.client.QueryRow(ctx, q, id).Scan(
&s.Id, &s.Logo, &s.Title, &s.Id, &s.Logo, &title,
&s.ContentTm, &s.ContentRu, &s.ContentEn, &contentTm, &contentRu, &contentEn,
&s.CreatedAt, &s.CreatedAt,
) )
if err != nil { if err != nil {
return s, err return s, err
} }
s.Title = title.Pick(lang)
s.Content = users.PickContent(lang, contentTm, contentRu, contentEn)
return s, nil return s, nil
} }
func (r repository) GetCurrency(ctx context.Context) (users.CurrencyDTO, error) { func (r repository) GetCurrency(ctx context.Context, lang string) (users.CurrencyDTO, error) {
var cu users.CurrencyDTO var cu users.CurrencyDTO
lang = users.NormalizeLang(lang)
var title users.Language
var contentTm, contentRu, contentEn string
q := ` SELECT q := ` SELECT
id, title, id, title,
@@ -250,13 +273,15 @@ func (r repository) GetCurrency(ctx context.Context) (users.CurrencyDTO, error)
LIMIT 1;` LIMIT 1;`
err := r.client.QueryRow(ctx, q).Scan( err := r.client.QueryRow(ctx, q).Scan(
&cu.Id, &cu.Title, &cu.Id, &title,
&cu.Content.Tm, &cu.Content.Ru, &cu.Content.En, &contentTm, &contentRu, &contentEn,
&cu.Path, &cu.CreatedAt, &cu.Path, &cu.CreatedAt,
) )
if err != nil { if err != nil {
return cu, err return cu, err
} }
cu.Title = title.Pick(lang)
cu.Content = users.PickContent(lang, contentTm, contentRu, contentEn)
return cu, nil return cu, nil
} }
@@ -278,8 +303,12 @@ func (r repository) GetSetting(ctx context.Context) (users.SettingDTO, error) {
return s, nil return s, nil
} }
func (r repository) GetSubCategoryById(ctx context.Context, id int) (users.SubCategoryDTO, error) { func (r repository) GetSubCategoryById(ctx context.Context, id int, lang string) (users.SubCategoryDTO, error) {
var sc users.SubCategoryDTO var sc users.SubCategoryDTO
lang = users.NormalizeLang(lang)
var name users.Language
var contentEn, contentTm, contentRu string
q := ` SELECT q := ` SELECT
sc.id, sc.category_id, sc.id, sc.category_id,
@@ -291,33 +320,41 @@ func (r repository) GetSubCategoryById(ctx context.Context, id int) (users.SubCa
err := r.client.QueryRow(ctx, q, id).Scan( err := r.client.QueryRow(ctx, q, id).Scan(
&sc.Id, &sc.CategoryId, &sc.Id, &sc.CategoryId,
&sc.Name, &sc.Count, &name, &sc.Count,
&sc.Content.En, &sc.Content.Tm, &sc.Content.Ru, &contentEn, &contentTm, &contentRu,
) )
if err != nil { if err != nil {
return sc, err return sc, err
} }
sc.Name = name.Pick(lang)
sc.Content = users.PickContent(lang, contentTm, contentRu, contentEn)
return sc, nil return sc, nil
} }
func (r repository) GetNewsById(ctx context.Context, id int) (users.NewsDTO, error) { func (r repository) GetNewsById(ctx context.Context, id int, lang string) (users.NewsDTO, error) {
var n users.NewsDTO var n users.NewsDTO
lang = users.NormalizeLang(lang)
var title users.Language
var contentEn, contentTm, contentRu string
q := ` SELECT q := ` SELECT
n.id, n.title, n.id, n.title,
n.date_release, n.img, n.date_release, n.img,
nc.en, nc.tm, nc.ru COALESCE(nc.en, ''), COALESCE(nc.tm, ''), COALESCE(nc.ru, '')
FROM news n FROM news n
LEFT JOIN news_content nc ON n.id = nc.news_id LEFT JOIN news_content nc ON n.id = nc.news_id
WHERE n.id = $1;` WHERE n.id = $1;`
err := r.client.QueryRow(ctx, q, id).Scan( err := r.client.QueryRow(ctx, q, id).Scan(
&n.Id, &n.Title, &n.Id, &title,
&n.DataRelease, &n.Image, &n.DataRelease, &n.Image,
&n.Content.En, &n.Content.Tm, &n.Content.Ru, &contentEn, &contentTm, &contentRu,
) )
if err != nil { if err != nil {
return n, err return n, err
} }
n.Title = title.Pick(lang)
n.Content = users.PickContent(lang, contentTm, contentRu, contentEn)
return n, nil return n, nil
} }

View File

@@ -1,6 +1,9 @@
package users package users
import "time" import (
"strings"
"time"
)
type DataNewsDTO struct { type DataNewsDTO struct {
News []NewsDTO `json:"news"` News []NewsDTO `json:"news"`
@@ -9,31 +12,81 @@ type DataNewsDTO struct {
type NewsDTO struct { type NewsDTO struct {
Id int `json:"id"` Id int `json:"id"`
Title Language `json:"title"` Title string `json:"title"`
Content Language `json:"content"` Content string `json:"content,omitempty"`
Image string `json:"imagePath"` Image string `json:"imagePath"`
DataRelease time.Time `json:"dateRelease"` DataRelease time.Time `json:"dateRelease,omitzero"`
} }
// Language is used when scanning multilingual JSON from the database.
type Language struct { type Language struct {
En string `json:"en"` En string `json:"en,omitempty"`
Ru string `json:"ru"` Ru string `json:"ru,omitempty"`
Tm string `json:"tm"` Tm string `json:"tm,omitempty"`
}
func NormalizeLang(lang string) string {
switch strings.ToLower(strings.TrimSpace(lang)) {
case "ru", "en", "tm":
return strings.ToLower(strings.TrimSpace(lang))
default:
return "tm"
}
}
func (l Language) Pick(lang string) string {
switch NormalizeLang(lang) {
case "ru":
if l.Ru != "" {
return l.Ru
}
case "en":
if l.En != "" {
return l.En
}
}
if l.Tm != "" {
return l.Tm
}
if l.Ru != "" {
return l.Ru
}
return l.En
}
func PickContent(lang, tm, ru, en string) string {
switch NormalizeLang(lang) {
case "ru":
if ru != "" {
return ru
}
case "en":
if en != "" {
return en
}
}
if tm != "" {
return tm
}
if ru != "" {
return ru
}
return en
} }
type CategoryDTO struct { type CategoryDTO struct {
Id int `json:"id"` Id int `json:"id"`
Name Language `json:"name"` Name string `json:"name"`
Image string `json:"imagePath"` Image string `json:"imagePath,omitempty"`
SubCategories []SubCategoryDTO `json:"subCategories"` SubCategories []SubCategoryDTO `json:"subCategories"`
} }
type SubCategoryDTO struct { type SubCategoryDTO struct {
Id int `json:"id"` Id int `json:"id"`
CategoryId int `json:"categoryId"` CategoryId int `json:"categoryId"`
Name Language `json:"name"` Name string `json:"name"`
Content Language `json:"content"` Content string `json:"content,omitempty"`
Count int `json:"count"` Count int `json:"count,omitempty"`
} }
type DataBannerDTO struct { type DataBannerDTO struct {
@@ -48,12 +101,10 @@ type BannerListItemDTO struct {
type BannerDTO struct { type BannerDTO struct {
Id int `json:"id"` Id int `json:"id"`
Title Language `json:"title"` Title string `json:"title"`
ContentTm string `json:"contentTm"` Content string `json:"content,omitempty"`
ContentRu string `json:"contentRu"`
ContentEn string `json:"contentEn"`
Image string `json:"imagePath"` Image string `json:"imagePath"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt,omitzero"`
} }
type DataStaticDTO struct { type DataStaticDTO struct {
@@ -64,26 +115,24 @@ type DataStaticDTO struct {
type StaticDTO struct { type StaticDTO struct {
Id int `json:"id"` Id int `json:"id"`
Logo string `json:"logo"` Logo string `json:"logo"`
Title Language `json:"title"` Title string `json:"title"`
ContentTm string `json:"contentTm"` Content string `json:"content,omitempty"`
ContentRu string `json:"contentRu"` CreatedAt time.Time `json:"createdAt,omitzero"`
ContentEn string `json:"contentEn"`
CreatedAt time.Time `json:"createdAt"`
} }
type CurrencyDTO struct { type CurrencyDTO struct {
Id int `json:"id"` Id int `json:"id"`
Title Language `json:"title"` Title string `json:"title"`
Content Language `json:"content"` Content string `json:"content,omitempty"`
Path string `json:"path"` Path string `json:"path,omitempty"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt,omitzero"`
} }
type SettingDTO struct { type SettingDTO struct {
UUID string `json:"UUID"` UUID string `json:"UUID,omitempty"`
LogoR string `json:"logoR"` LogoR string `json:"logoR"`
PhoneNumber string `json:"phoneNumber"` PhoneNumber string `json:"phoneNumber"`
FaxNumber string `json:"faxNumber"` FaxNumber string `json:"faxNumber"`
HelpNumber string `json:"helpNumber"` HelpNumber string `json:"helpNumber"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt,omitzero"`
} }

View File

@@ -48,6 +48,10 @@ func (h *handler) Register(router *gin.RouterGroup) {
router.GET(getSettingURL, h.GetSetting) router.GET(getSettingURL, h.GetSetting)
} }
func queryLang(c *gin.Context) string {
return NormalizeLang(c.Query("lang"))
}
// ================================================================================= // =================================================================================
// GetNews godoc // GetNews godoc
@@ -55,8 +59,9 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Tags news // @Tags news
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param limit query int false "limit" // @Param limit query int false "limit"
// @Param page query int false "page" // @Param page query int false "page"
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {object} DataNewsDTO // @Success 200 {object} DataNewsDTO
// @Router /client/users/news [get] // @Router /client/users/news [get]
func (h *handler) GetNews(c *gin.Context) { func (h *handler) GetNews(c *gin.Context) {
@@ -66,7 +71,7 @@ func (h *handler) GetNews(c *gin.Context) {
limit, _ := strconv.Atoi(limitS) limit, _ := strconv.Atoi(limitS)
page, _ := strconv.Atoi(pageS) page, _ := strconv.Atoi(pageS)
result, err := h.repository.GetNews(c.Request.Context(), limit, page) result, err := h.repository.GetNews(c.Request.Context(), limit, page, queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
@@ -83,6 +88,7 @@ func (h *handler) GetNews(c *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param id path int true "news ID" // @Param id path int true "news ID"
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {object} NewsDTO // @Success 200 {object} NewsDTO
// @Router /client/users/news/{id} [get] // @Router /client/users/news/{id} [get]
func (h *handler) GetOneNews(c *gin.Context) { func (h *handler) GetOneNews(c *gin.Context) {
@@ -92,7 +98,7 @@ func (h *handler) GetOneNews(c *gin.Context) {
return return
} }
result, err := h.repository.GetNewsById(c.Request.Context(), id) result, err := h.repository.GetNewsById(c.Request.Context(), id, queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
@@ -109,6 +115,7 @@ func (h *handler) GetOneNews(c *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param id path int true "sub-category ID" // @Param id path int true "sub-category ID"
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {object} SubCategoryDTO // @Success 200 {object} SubCategoryDTO
// @Router /client/users/sub-categories/{id} [get] // @Router /client/users/sub-categories/{id} [get]
func (h *handler) GetSubCategory(c *gin.Context) { func (h *handler) GetSubCategory(c *gin.Context) {
@@ -118,7 +125,7 @@ func (h *handler) GetSubCategory(c *gin.Context) {
return return
} }
result, err := h.repository.GetSubCategoryById(c.Request.Context(), id) result, err := h.repository.GetSubCategoryById(c.Request.Context(), id, queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
@@ -162,6 +169,7 @@ func (h *handler) GetBanners(c *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param id path int true "banner ID" // @Param id path int true "banner ID"
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {object} BannerDTO // @Success 200 {object} BannerDTO
// @Router /client/users/banners/{id} [get] // @Router /client/users/banners/{id} [get]
func (h *handler) GetOneBanner(c *gin.Context) { func (h *handler) GetOneBanner(c *gin.Context) {
@@ -171,7 +179,7 @@ func (h *handler) GetOneBanner(c *gin.Context) {
return return
} }
result, err := h.repository.GetBannerById(c.Request.Context(), id) result, err := h.repository.GetBannerById(c.Request.Context(), id, queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
@@ -187,8 +195,9 @@ func (h *handler) GetOneBanner(c *gin.Context) {
// @Tags statics // @Tags statics
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param limit query int false "limit" // @Param limit query int false "limit"
// @Param page query int false "page" // @Param page query int false "page"
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {object} DataStaticDTO // @Success 200 {object} DataStaticDTO
// @Router /client/users/static [get] // @Router /client/users/static [get]
func (h *handler) GetStatics(c *gin.Context) { func (h *handler) GetStatics(c *gin.Context) {
@@ -198,7 +207,7 @@ func (h *handler) GetStatics(c *gin.Context) {
limit, _ := strconv.Atoi(limitS) limit, _ := strconv.Atoi(limitS)
page, _ := strconv.Atoi(pageS) page, _ := strconv.Atoi(pageS)
result, err := h.repository.GetStatics(c.Request.Context(), limit, page) result, err := h.repository.GetStatics(c.Request.Context(), limit, page, queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
@@ -215,6 +224,7 @@ func (h *handler) GetStatics(c *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param id path int true "static ID" // @Param id path int true "static ID"
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {object} StaticDTO // @Success 200 {object} StaticDTO
// @Router /client/users/static/{id} [get] // @Router /client/users/static/{id} [get]
func (h *handler) GetOneStatic(c *gin.Context) { func (h *handler) GetOneStatic(c *gin.Context) {
@@ -224,7 +234,7 @@ func (h *handler) GetOneStatic(c *gin.Context) {
return return
} }
result, err := h.repository.GetStaticById(c.Request.Context(), id) result, err := h.repository.GetStaticById(c.Request.Context(), id, queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
@@ -236,14 +246,15 @@ func (h *handler) GetOneStatic(c *gin.Context) {
} }
// GetCurrency godoc // GetCurrency godoc
// @Description latest currency content (title + HTML table per language) // @Description latest currency content (title + HTML table for requested language)
// @Tags currency // @Tags currency
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {object} CurrencyDTO // @Success 200 {object} CurrencyDTO
// @Router /client/users/currency [get] // @Router /client/users/currency [get]
func (h *handler) GetCurrency(c *gin.Context) { func (h *handler) GetCurrency(c *gin.Context) {
result, err := h.repository.GetCurrency(c.Request.Context()) result, err := h.repository.GetCurrency(c.Request.Context(), queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
@@ -278,10 +289,11 @@ func (h *handler) GetSetting(c *gin.Context) {
// @Tags categories // @Tags categories
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param lang query string false "tm|ru|en (default tm)"
// @Success 200 {array} CategoryDTO // @Success 200 {array} CategoryDTO
// @Router /client/users/categories [get] // @Router /client/users/categories [get]
func (h *handler) GetCategories(c *gin.Context) { func (h *handler) GetCategories(c *gin.Context) {
result, err := h.repository.GetCategories(c.Request.Context()) result, err := h.repository.GetCategories(c.Request.Context(), queryLang(c))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return

View File

@@ -3,18 +3,18 @@ package users
import "context" import "context"
type Repository interface { type Repository interface {
GetNews(ctx context.Context, limit, page int) (DataNewsDTO, error) GetNews(ctx context.Context, limit, page int, lang string) (DataNewsDTO, error)
GetNewsById(ctx context.Context, id int) (NewsDTO, error) GetNewsById(ctx context.Context, id int, lang string) (NewsDTO, error)
GetCategories(ctx context.Context) ([]CategoryDTO, error) GetCategories(ctx context.Context, lang string) ([]CategoryDTO, error)
GetSubCategoryById(ctx context.Context, id int) (SubCategoryDTO, error) GetSubCategoryById(ctx context.Context, id int, lang string) (SubCategoryDTO, error)
GetBanners(ctx context.Context, limit, page int) (DataBannerDTO, error) GetBanners(ctx context.Context, limit, page int) (DataBannerDTO, error)
GetBannerById(ctx context.Context, id int) (BannerDTO, error) GetBannerById(ctx context.Context, id int, lang string) (BannerDTO, error)
GetStatics(ctx context.Context, limit, page int) (DataStaticDTO, error) GetStatics(ctx context.Context, limit, page int, lang string) (DataStaticDTO, error)
GetStaticById(ctx context.Context, id int) (StaticDTO, error) GetStaticById(ctx context.Context, id int, lang string) (StaticDTO, error)
GetCurrency(ctx context.Context) (CurrencyDTO, error) GetCurrency(ctx context.Context, lang string) (CurrencyDTO, error)
GetSetting(ctx context.Context) (SettingDTO, error) GetSetting(ctx context.Context) (SettingDTO, error)
} }

View File

@@ -39,19 +39,13 @@ function getData(url = '') {
.then(response => response.json()); .then(response => response.json());
} }
function localizedContent(item) { function getCurrentLang() {
if (window.locale === 'ru') { return window.locale || 'tm';
return item.contentRu
}
if (window.locale === 'en') {
return item.contentEn
}
return item.contentTm
} }
function getCurrentLang() function withLang(url) {
{ const sep = url.includes('?') ? '&' : '?';
return window.location.search.includes('lang=ru') ? 'ru' : ''; return url + sep + 'lang=' + getCurrentLang();
} }
function isHomepage() { function isHomepage() {
@@ -127,7 +121,7 @@ async function fetchMenuItems() {
const container = $_ID('menu-items-container') const container = $_ID('menu-items-container')
const sideBarMenuItems = $_ID('sidebar-menu-items') const sideBarMenuItems = $_ID('sidebar-menu-items')
const response = await getData('/api/v1/client/users/categories') const response = await getData(withLang('/api/v1/client/users/categories'))
response.data.forEach(menuItem => { response.data.forEach(menuItem => {
let subcategoriesTemplate = ''; let subcategoriesTemplate = '';
@@ -140,7 +134,7 @@ async function fetchMenuItems() {
<a class="bg-trasparent lg:bg-white" href="${ <a class="bg-trasparent lg:bg-white" href="${
'/page.html?id=' + subcategory.id + '&lang=' + getCurrentLang() '/page.html?id=' + subcategory.id + '&lang=' + getCurrentLang()
}"> }">
${subcategory.name[window.locale]} ${subcategory.name}
</a> </a>
</li> </li>
`; `;
@@ -148,7 +142,7 @@ async function fetchMenuItems() {
}) })
} }
const categoryName = (menuItem.name[window.locale] || '').toUpperCase() const categoryName = (menuItem.name || '').toUpperCase()
container.insertAdjacentHTML('beforeend', ` container.insertAdjacentHTML('beforeend', `
<div class="dropdown" style="z-index:1000"> <div class="dropdown" style="z-index:1000">
@@ -222,16 +216,16 @@ async function fetchMiniSliders() {
async function fetchMiniCategories() { async function fetchMiniCategories() {
const miniCategoryContainer = $_ID('mini-category-content-container') const miniCategoryContainer = $_ID('mini-category-content-container')
const response = await getData('/api/v1/client/users/static') const response = await getData(withLang('/api/v1/client/users/static'))
removeByClassName('mini-categories-loader') removeByClassName('mini-categories-loader')
response.data.statics.forEach(category => { response.data.statics.forEach(category => {
miniCategoryContainer.insertAdjacentHTML('beforeend', ` miniCategoryContainer.insertAdjacentHTML('beforeend', `
<a href="/action.html?id=${category.id + '&lang=' + getCurrentLang()}"> <a href="/action.html?id=${category.id}&lang=${getCurrentLang()}">
<div class="bg-gray-100 flex flex-1 flex-col items-center gap-3 py-7 px-3 mt-2 rounded-md"> <div class="bg-gray-100 flex flex-1 flex-col items-center gap-3 py-7 px-3 mt-2 rounded-md">
<img src="${baseUrl() + category.logo}" class="w-16 h-16" alt="..." loading="lazy"> <img src="${baseUrl() + category.logo}" class="w-16 h-16" alt="..." loading="lazy">
<h1 class="text-gray-700 uppercase text-center">${category.title[window.locale]}</h1> <h1 class="text-gray-700 uppercase text-center">${category.title}</h1>
</div> </div>
</a> </a>
`) `)
@@ -240,10 +234,10 @@ async function fetchMiniCategories() {
async function fetchCurrencies() { async function fetchCurrencies() {
const currencyTable = $_ID('currency-table') const currencyTable = $_ID('currency-table')
const response = await getData('/api/v1/client/users/currency') const response = await getData(withLang('/api/v1/client/users/currency'))
removeByClassName('currency-table-loader') removeByClassName('currency-table-loader')
currencyTable.innerHTML = response.data.content[window.locale]; currencyTable.innerHTML = response.data.content;
currencyTable.querySelector('table').classList.add('table-auto', 'bg-gray-500', 'text-sm', 'text-white', 'w-full') currencyTable.querySelector('table').classList.add('table-auto', 'bg-gray-500', 'text-sm', 'text-white', 'w-full')
Array.from(currencyTable.getElementsByTagName('th')).forEach(item => { Array.from(currencyTable.getElementsByTagName('th')).forEach(item => {
@@ -258,22 +252,22 @@ async function fetchCurrencies() {
} }
}) })
$_ID('currency-message-container').innerHTML = response.data.title[window.locale]; $_ID('currency-message-container').innerHTML = response.data.title;
} }
async function fetchNews() { async function fetchNews() {
const newsContainer = $_ID('news-content-container') const newsContainer = $_ID('news-content-container')
const response = await getData('/api/v1/client/users/news?limit=6&page=1') const response = await getData(withLang('/api/v1/client/users/news?limit=6&page=1'))
removeByClassName('news-loaders') removeByClassName('news-loaders')
response.data.news.forEach(news => { response.data.news.forEach(news => {
newsContainer.insertAdjacentHTML('beforeend', ` newsContainer.insertAdjacentHTML('beforeend', `
<a href="news.html?id=${news.id + '&lang=' + getCurrentLang()}"> <a href="news.html?id=${news.id}&lang=${getCurrentLang()}">
<div class="flex flex-col px-3 mt-3"> <div class="flex flex-col px-3 mt-3">
<div class="h-60"> <div class="h-60">
<img src="${baseUrl() + news.imagePath}" class="news-img-size" alt="..." loading="lazy"> <img src="${baseUrl() + news.imagePath}" class="news-img-size" alt="..." loading="lazy">
</div> </div>
<h1 class="text-base text-gray-800 mt-2 py-2 px-1 text-center">${news.title[window.locale]}</h1> <h1 class="text-base text-gray-800 mt-2 py-2 px-1 text-center">${news.title}</h1>
</div> </div>
</a> </a>
`) `)
@@ -289,17 +283,17 @@ async function fetchSubCategory() {
const pageContent = $_ID('page-content'); const pageContent = $_ID('page-content');
const response = await getData('/api/v1/client/users/sub-categories/' + pageURL.searchParams.get('id')) const response = await getData(withLang('/api/v1/client/users/sub-categories/' + pageURL.searchParams.get('id')))
removeByClassName('page-content-loader') removeByClassName('page-content-loader')
pageContent.innerHTML = ` pageContent.innerHTML = `
<h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold"> <h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold">
${response.data.name[window.locale]} ${response.data.name}
</h1> </h1>
<div> <div>
${response.data.content[window.locale]} ${response.data.content}
</div> </div>
`; `;
} }
@@ -313,7 +307,7 @@ async function fetchBannerContent() {
const pageContent = $_ID('page-content'); const pageContent = $_ID('page-content');
const response = await getData('/api/v1/client/users/banners/' + pageURL.searchParams.get('id')) const response = await getData(withLang('/api/v1/client/users/banners/' + pageURL.searchParams.get('id')))
const banner = response.data const banner = response.data
removeByClassName('page-content-loader') removeByClassName('page-content-loader')
@@ -324,7 +318,7 @@ async function fetchBannerContent() {
pageContent.innerHTML = ` pageContent.innerHTML = `
<h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold"> <h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold">
${banner.title[window.locale]} ${banner.title}
</h1> </h1>
<div> <div>
@@ -332,7 +326,7 @@ async function fetchBannerContent() {
</div> </div>
<div> <div>
${localizedContent(banner)} ${banner.content || ''}
</div> </div>
`; `;
} }
@@ -346,17 +340,17 @@ async function fetchMiniCategory() {
const pageContent = $_ID('page-content'); const pageContent = $_ID('page-content');
const response = await getData('/api/v1/client/users/static/' + pageURL.searchParams.get('id')) const response = await getData(withLang('/api/v1/client/users/static/' + pageURL.searchParams.get('id')))
removeByClassName('page-content-loader') removeByClassName('page-content-loader')
pageContent.innerHTML = ` pageContent.innerHTML = `
<h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold"> <h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold">
${response.data.title[window.locale]} ${response.data.title}
</h1> </h1>
<div> <div>
${localizedContent(response.data)} ${response.data.content || ''}
</div> </div>
`; `;
} }
@@ -370,13 +364,13 @@ async function fetchNewsContent() {
const pageContent = $_ID('page-content'); const pageContent = $_ID('page-content');
const response = await getData('/api/v1/client/users/news/' + pageURL.searchParams.get('id')) const response = await getData(withLang('/api/v1/client/users/news/' + pageURL.searchParams.get('id')))
removeByClassName('page-content-loader') removeByClassName('page-content-loader')
pageContent.innerHTML = ` pageContent.innerHTML = `
<h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold"> <h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold">
${response.data.title[window.locale]} ${response.data.title}
</h1> </h1>
<div class="mb-5"> <div class="mb-5">
@@ -388,7 +382,7 @@ async function fetchNewsContent() {
${ new Date(response.data.dateRelease).toLocaleDateString('en-GB').replace(/\//g, '.') + 'ý' } ${ new Date(response.data.dateRelease).toLocaleDateString('en-GB').replace(/\//g, '.') + 'ý' }
</p> </p>
${response.data.content[window.locale]} ${response.data.content || ''}
</div> </div>
`; `;
} }