feat: oapi gen

This commit is contained in:
gelik 2023-05-17 06:39:29 +03:00
parent 35541bb9a3
commit 8bfd447d46
9 changed files with 601 additions and 324 deletions

@ -4,6 +4,7 @@ run:
- \.pb\.go$ - \.pb\.go$
- \.pb\.validate\.go$ - \.pb\.validate\.go$
- \.pb\.gw\.go$ - \.pb\.gw\.go$
- \.gen\.go$
skip-dirs: skip-dirs:
- mocks - mocks

@ -1,4 +1,4 @@
// Package api provides primitives to interact with the openapi HTTP API. // Package swagger provides primitives to interact with the openapi HTTP API.
// //
// Code generated by github.com/deepmap/oapi-codegen version v1.12.4 DO NOT EDIT. // Code generated by github.com/deepmap/oapi-codegen version v1.12.4 DO NOT EDIT.
package swagger package swagger
@ -12,133 +12,12 @@ import (
"net/url" "net/url"
"path" "path"
"strings" "strings"
"time"
"github.com/deepmap/oapi-codegen/pkg/runtime" "github.com/deepmap/oapi-codegen/pkg/runtime"
"github.com/getkin/kin-openapi/openapi3" "github.com/getkin/kin-openapi/openapi3"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
// Defines values for RecordType.
const (
BuyCart RecordType = "buyCart"
DeclinedPayment RecordType = "declinedPayment"
SubsriptionEnd RecordType = "subsriptionEnd"
SuccessfulPayment RecordType = "successfulPayment"
TimeoutPayment RecordType = "timeoutPayment"
)
// Account defines model for Account.
type Account struct {
Id *string `json:"_id,omitempty"`
Cart *Cart `json:"cart,omitempty"`
IsDeleted *bool `json:"isDeleted,omitempty"`
UserId *string `json:"userId,omitempty"`
Wallet *Wallet `json:"wallet,omitempty"`
}
// Cart defines model for Cart.
type Cart = []string
// Record defines model for Record.
type Record struct {
Comment *string `json:"comment,omitempty"`
CreatedAt *time.Time `json:"createdAt,omitempty"`
Id *string `json:"id,omitempty"`
// Subject я пока не могу предположить, какие будут фильтры по истории, поэтому предлагаю в это поле просто класть строку с json. ибо для каждого типа записи она своя.
Subject *string `json:"subject,omitempty"`
Type *RecordType `json:"type,omitempty"`
UserId *string `json:"userId,omitempty"`
}
// RecordType defines model for Record.Type.
type RecordType string
// Wallet defines model for Wallet.
type Wallet struct {
Cash *int64 `json:"cash,omitempty"`
Currency *string `json:"currency,omitempty"`
// Money деньги на счету в копейках. Чтобы при перессчётах не возникало денег изниоткуда. фиксируемся к одной валюте, она будет внутренней, никому её не покажем
Money *int64 `json:"money,omitempty"`
}
// PaginationAccountsParams defines parameters for PaginationAccounts.
type PaginationAccountsParams struct {
// P Номер страницы, начиная с 0
P *int `form:"p,omitempty" json:"p,omitempty"`
// S размер страницы
S *int `form:"s,omitempty" json:"s,omitempty"`
}
// RemoveFromCartParams defines parameters for RemoveFromCart.
type RemoveFromCartParams struct {
Id string `form:"id" json:"id"`
}
// Add2cartJSONBody defines parameters for Add2cart.
type Add2cartJSONBody struct {
Id *string `json:"id,omitempty"`
}
// PayCartJSONBody defines parameters for PayCart.
type PayCartJSONBody struct {
// Id айдишник для того, чтобы указать сервису оплаты, какой юзер оплатил
Id *string `json:"id,omitempty"`
}
// UpdateCurrenciesJSONBody defines parameters for UpdateCurrencies.
type UpdateCurrenciesJSONBody = []string
// GetHistoryParams defines parameters for GetHistory.
type GetHistoryParams struct {
// P Номер страницы, начиная с 0
P *int `form:"p,omitempty" json:"p,omitempty"`
// S размер страницы
S *int `form:"s,omitempty" json:"s,omitempty"`
}
// ChangeCurrencyJSONBody defines parameters for ChangeCurrency.
type ChangeCurrencyJSONBody struct {
Currency *string `json:"currency,omitempty"`
}
// RequestMoneyJSONBody defines parameters for RequestMoney.
type RequestMoneyJSONBody struct {
Cash *int `json:"cash,omitempty"`
}
// PutMoneyJSONBody defines parameters for PutMoney.
type PutMoneyJSONBody struct {
Cash *int `json:"cash,omitempty"`
Currency *string `json:"currency,omitempty"`
Id *string `json:"id,omitempty"`
}
// Add2cartJSONRequestBody defines body for Add2cart for application/json ContentType.
type Add2cartJSONRequestBody Add2cartJSONBody
// PayCartJSONRequestBody defines body for PayCart for application/json ContentType.
type PayCartJSONRequestBody PayCartJSONBody
// UpdateCurrenciesJSONRequestBody defines body for UpdateCurrencies for application/json ContentType.
type UpdateCurrenciesJSONRequestBody = UpdateCurrenciesJSONBody
// Add2historyJSONRequestBody defines body for Add2history for application/json ContentType.
type Add2historyJSONRequestBody = Record
// ChangeCurrencyJSONRequestBody defines body for ChangeCurrency for application/json ContentType.
type ChangeCurrencyJSONRequestBody ChangeCurrencyJSONBody
// RequestMoneyJSONRequestBody defines body for RequestMoney for application/json ContentType.
type RequestMoneyJSONRequestBody RequestMoneyJSONBody
// PutMoneyJSONRequestBody defines body for PutMoney for application/json ContentType.
type PutMoneyJSONRequestBody PutMoneyJSONBody
// ServerInterface represents all server handlers. // ServerInterface represents all server handlers.
type ServerInterface interface { type ServerInterface interface {
// удалить собственный аккаунт // удалить собственный аккаунт
@ -147,23 +26,23 @@ type ServerInterface interface {
// Получение текущего аккаунта юзера // Получение текущего аккаунта юзера
// (GET /account) // (GET /account)
GetAccount(ctx echo.Context) error GetAccount(ctx echo.Context) error
// создать новый аккаунт // Создать новый аккаунт
// (POST /account) // (POST /account)
AddAccount(ctx echo.Context) error AddAccount(ctx echo.Context) error
// удалить аккаунт по айди // Удалить аккаунт по айди
// (DELETE /account/{accountId}) // (DELETE /account/{accountId})
DeleteDirectAccount(ctx echo.Context, accountId string) error DeleteDirectAccount(ctx echo.Context, accountId string) error
// получить аккаунт по айди // Получить аккаунт по ID
// (GET /account/{accountId}) // (GET /account/{accountId})
GetDirectAccount(ctx echo.Context, accountId string) error GetDirectAccount(ctx echo.Context, accountId string) error
// списко аккаунтов с пагинацией // списко аккаунтов с пагинацией
// (GET /accounts) // (GET /accounts)
PaginationAccounts(ctx echo.Context, params PaginationAccountsParams) error PaginationAccounts(ctx echo.Context, params PaginationAccountsParams) error
// удаляем из корзины тариф // Удаляем из корзины тариф
// (DELETE /cart) // (DELETE /cart)
RemoveFromCart(ctx echo.Context, params RemoveFromCartParams) error RemoveFromCart(ctx echo.Context, params RemoveFromCartParams) error
// добавляем в корзину тариф // Добавляем в корзину тариф
// (PUT /cart) // (PATCH /cart)
Add2cart(ctx echo.Context) error Add2cart(ctx echo.Context) error
// оплатить козину // оплатить козину
// (POST /cart/pay) // (POST /cart/pay)
@ -172,22 +51,22 @@ type ServerInterface interface {
// (GET /currencies) // (GET /currencies)
GetCurrencies(ctx echo.Context) error GetCurrencies(ctx echo.Context) error
// обновляет список одобренных валют // обновляет список одобренных валют
// (PATCH /currencies) // (PUT /currencies)
UpdateCurrencies(ctx echo.Context) error UpdateCurrencies(ctx echo.Context) error
// получение лога событий связанных с аккаунтом // Получение лога событий связанных с аккаунтом
// (GET /history) // (GET /history)
GetHistory(ctx echo.Context, params GetHistoryParams) error GetHistory(ctx echo.Context, params GetHistoryParams) error
// публикация лога в истории // Публикация лога в истории
// (POST /history) // (POST /history)
Add2history(ctx echo.Context) error Add2history(ctx echo.Context) error
// изменить валюту кошелька // Запрос на получение ссылки на оплату
// (GET /wallet)
RequestMoney(ctx echo.Context, params RequestMoneyParams) error
// Изменить валюту кошелька
// (PATCH /wallet) // (PATCH /wallet)
ChangeCurrency(ctx echo.Context) error ChangeCurrency(ctx echo.Context) error
// запрос на получение ссылки на оплату // Зачислить деньги на кошелёк
// (POST /wallet) // (POST /wallet)
RequestMoney(ctx echo.Context) error
// зачислить деньги на кошелёк
// (PUT /wallet)
PutMoney(ctx echo.Context) error PutMoney(ctx echo.Context) error
} }
@ -200,6 +79,8 @@ type ServerInterfaceWrapper struct {
func (w *ServerInterfaceWrapper) DeleteAccount(ctx echo.Context) error { func (w *ServerInterfaceWrapper) DeleteAccount(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.DeleteAccount(ctx) err = w.Handler.DeleteAccount(ctx)
return err return err
@ -209,6 +90,8 @@ func (w *ServerInterfaceWrapper) DeleteAccount(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) GetAccount(ctx echo.Context) error { func (w *ServerInterfaceWrapper) GetAccount(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.GetAccount(ctx) err = w.Handler.GetAccount(ctx)
return err return err
@ -218,6 +101,8 @@ func (w *ServerInterfaceWrapper) GetAccount(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) AddAccount(ctx echo.Context) error { func (w *ServerInterfaceWrapper) AddAccount(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.AddAccount(ctx) err = w.Handler.AddAccount(ctx)
return err return err
@ -234,6 +119,8 @@ func (w *ServerInterfaceWrapper) DeleteDirectAccount(ctx echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter accountId: %s", err)) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter accountId: %s", err))
} }
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.DeleteDirectAccount(ctx, accountId) err = w.Handler.DeleteDirectAccount(ctx, accountId)
return err return err
@ -250,6 +137,8 @@ func (w *ServerInterfaceWrapper) GetDirectAccount(ctx echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter accountId: %s", err)) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter accountId: %s", err))
} }
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.GetDirectAccount(ctx, accountId) err = w.Handler.GetDirectAccount(ctx, accountId)
return err return err
@ -261,18 +150,18 @@ func (w *ServerInterfaceWrapper) PaginationAccounts(ctx echo.Context) error {
// Parameter object where we will unmarshal all parameters from the context // Parameter object where we will unmarshal all parameters from the context
var params PaginationAccountsParams var params PaginationAccountsParams
// ------------- Optional query parameter "p" ------------- // ------------- Optional query parameter "page" -------------
err = runtime.BindQueryParameter("form", false, false, "p", ctx.QueryParams(), &params.P) err = runtime.BindQueryParameter("form", false, false, "page", ctx.QueryParams(), &params.Page)
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter p: %s", err)) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter page: %s", err))
} }
// ------------- Optional query parameter "s" ------------- // ------------- Optional query parameter "limit" -------------
err = runtime.BindQueryParameter("form", false, false, "s", ctx.QueryParams(), &params.S) err = runtime.BindQueryParameter("form", false, false, "limit", ctx.QueryParams(), &params.Limit)
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter s: %s", err)) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter limit: %s", err))
} }
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
@ -284,6 +173,8 @@ func (w *ServerInterfaceWrapper) PaginationAccounts(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) RemoveFromCart(ctx echo.Context) error { func (w *ServerInterfaceWrapper) RemoveFromCart(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Parameter object where we will unmarshal all parameters from the context // Parameter object where we will unmarshal all parameters from the context
var params RemoveFromCartParams var params RemoveFromCartParams
// ------------- Required query parameter "id" ------------- // ------------- Required query parameter "id" -------------
@ -302,6 +193,8 @@ func (w *ServerInterfaceWrapper) RemoveFromCart(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) Add2cart(ctx echo.Context) error { func (w *ServerInterfaceWrapper) Add2cart(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.Add2cart(ctx) err = w.Handler.Add2cart(ctx)
return err return err
@ -311,6 +204,8 @@ func (w *ServerInterfaceWrapper) Add2cart(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) PayCart(ctx echo.Context) error { func (w *ServerInterfaceWrapper) PayCart(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.PayCart(ctx) err = w.Handler.PayCart(ctx)
return err return err
@ -338,6 +233,8 @@ func (w *ServerInterfaceWrapper) UpdateCurrencies(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) GetHistory(ctx echo.Context) error { func (w *ServerInterfaceWrapper) GetHistory(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Parameter object where we will unmarshal all parameters from the context // Parameter object where we will unmarshal all parameters from the context
var params GetHistoryParams var params GetHistoryParams
// ------------- Optional query parameter "p" ------------- // ------------- Optional query parameter "p" -------------
@ -363,26 +260,41 @@ func (w *ServerInterfaceWrapper) GetHistory(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) Add2history(ctx echo.Context) error { func (w *ServerInterfaceWrapper) Add2history(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.Add2history(ctx) err = w.Handler.Add2history(ctx)
return err return err
} }
// ChangeCurrency converts echo context to params.
func (w *ServerInterfaceWrapper) ChangeCurrency(ctx echo.Context) error {
var err error
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.ChangeCurrency(ctx)
return err
}
// RequestMoney converts echo context to params. // RequestMoney converts echo context to params.
func (w *ServerInterfaceWrapper) RequestMoney(ctx echo.Context) error { func (w *ServerInterfaceWrapper) RequestMoney(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Parameter object where we will unmarshal all parameters from the context
var params RequestMoneyParams
// ------------- Required query parameter "cash" -------------
err = runtime.BindQueryParameter("form", true, true, "cash", ctx.QueryParams(), &params.Cash)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter cash: %s", err))
}
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.RequestMoney(ctx) err = w.Handler.RequestMoney(ctx, params)
return err
}
// ChangeCurrency converts echo context to params.
func (w *ServerInterfaceWrapper) ChangeCurrency(ctx echo.Context) error {
var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.ChangeCurrency(ctx)
return err return err
} }
@ -390,6 +302,8 @@ func (w *ServerInterfaceWrapper) RequestMoney(ctx echo.Context) error {
func (w *ServerInterfaceWrapper) PutMoney(ctx echo.Context) error { func (w *ServerInterfaceWrapper) PutMoney(ctx echo.Context) error {
var err error var err error
ctx.Set(BearerScopes, []string{""})
// Invoke the callback with all the unmarshalled arguments // Invoke the callback with all the unmarshalled arguments
err = w.Handler.PutMoney(ctx) err = w.Handler.PutMoney(ctx)
return err return err
@ -430,73 +344,79 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL
router.GET(baseURL+"/account/:accountId", wrapper.GetDirectAccount) router.GET(baseURL+"/account/:accountId", wrapper.GetDirectAccount)
router.GET(baseURL+"/accounts", wrapper.PaginationAccounts) router.GET(baseURL+"/accounts", wrapper.PaginationAccounts)
router.DELETE(baseURL+"/cart", wrapper.RemoveFromCart) router.DELETE(baseURL+"/cart", wrapper.RemoveFromCart)
router.PUT(baseURL+"/cart", wrapper.Add2cart) router.PATCH(baseURL+"/cart", wrapper.Add2cart)
router.POST(baseURL+"/cart/pay", wrapper.PayCart) router.POST(baseURL+"/cart/pay", wrapper.PayCart)
router.GET(baseURL+"/currencies", wrapper.GetCurrencies) router.GET(baseURL+"/currencies", wrapper.GetCurrencies)
router.PATCH(baseURL+"/currencies", wrapper.UpdateCurrencies) router.PUT(baseURL+"/currencies", wrapper.UpdateCurrencies)
router.GET(baseURL+"/history", wrapper.GetHistory) router.GET(baseURL+"/history", wrapper.GetHistory)
router.POST(baseURL+"/history", wrapper.Add2history) router.POST(baseURL+"/history", wrapper.Add2history)
router.GET(baseURL+"/wallet", wrapper.RequestMoney)
router.PATCH(baseURL+"/wallet", wrapper.ChangeCurrency) router.PATCH(baseURL+"/wallet", wrapper.ChangeCurrency)
router.POST(baseURL+"/wallet", wrapper.RequestMoney) router.POST(baseURL+"/wallet", wrapper.PutMoney)
router.PUT(baseURL+"/wallet", wrapper.PutMoney)
} }
// Base64 encoded, gzipped, json marshaled Swagger object // Base64 encoded, gzipped, json marshaled Swagger object
var swaggerSpec = []string{ var swaggerSpec = []string{
"H4sIAAAAAAAC/+xb3W4bx/V/lcH+/xcJSlFk4tax7hy5H7koELgwctEaxZocSpuSu8zuMq0qCBBF105A", "H4sIAAAAAAAC/+xbW28bxxX+K4NtHxKUpkhHiRO+OXbSukCBIKmRB0doVuRQ2oTcZXaXSVSDgCi6dgIp",
"2aofwC3Qm96uKK61IrnUK5x5o+Kcmf0eSrIkf6ToTUztzs6cOed3fudjJrtGy+n1HZvbvmds7Bpea5v3", "Vly0SB5qu2kK9LE0JVor3vQXzvyj4pyZ3Z29UKYuseUmLzZFzs6cOZfvXPe2UXWaLcfmtu8ZlduGV13n",
"TPp5v9VyBraPP/uu0+eub3F68Uerjf/wv5i9fpcbG8YXjbudZufu3SetzhfNVvvuvXt3Pr/XaDaNmuHv", "TZM+Xq1Wnbbt48eW67S461ucfviTVcP/+Jdms9XgRsV4s3SlXq5fubJarb9ZrtauvPXW8mtvlcplo2D4",
"9HGE57uWvWXs1YyW6dKU/+/yjrFh/N96tv66Wnx9E8fs1QzLe8C73OfF5Tpm1+PpzE8cp8tNG4cPPO5+", "Gy1c4fmuZa8ZnYJRNV0/8fSt4x6f89NlY6VgWD5vEj2ZM9QXpuuaG3Smy02f167SwXXHbZq+UTFqps8v",
"dQPR/mx2u/xS4b6Ro/b20hmcJ9/yFgm8qTZn+bznFQT5/UWSXOfVY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7LQXIzOpkgxpJkj148i4CefyP9HRDs8v0M1XG1Q80Eu1RdH2QdJ", "WzIGpBpaoKrQ/bwKNCFwPCHeT0eU/ZS1q4QuGh5AOmhIMmnv1VW3/gpVM/ZlPScqDUU1lqkad8OvYkM+",
"pr/3eO8/AQAA//8nG+8kJDMAAA==", "oKLfEIavqoOlsQ9UUS/QiMWdUkPNTPZmBzCToKGtLeqLH2DoPKVaZVj3EnfpFaGZLK2oaJ50OVHESMy+",
"qZltQpwpJbiHhLZRtSma9VY1I5LCfeoGH4bLCAHT78VIkFEFL4lDJJYx6c9mNPIVvkcgX0YISKjDeAqV",
"LjWVrxlk8PDaummvhXnfxrlVh/JftpAJ2AXuH6TDEtFVEzV6CocKkFI5GeCWnttAatZgpzIPTVjtz6rV",
"8Tg3ANhRnNF6ICdA+O9l/khOX1Zmj4GdOWCeP5VLWJ7upCTdh8qtDlSgEeUiI4YBBZOh6aZ0KxkXEOJk",
"WCxXP9BbQdqrQHmXSJWN21GsdE7IkH2DKzfoKZwEQ87/FbSLURCeyXfCptTMiTQg0eDop1zaRYai54ED",
"3yY7Zmew/u9kgC/bSmHEk3r9L8X7HAgg3ZJfZlAgPaqdnIY0cmpaqpklenAUBl6aX9JyjtB2cvbQegpk",
"8FGa4vrzlus3VMvVBXMe0DJasRs/ECa0nZXO/wIAAP//vkWxS/xAAAA=",
} }
// GetSwagger returns the content of the embedded swagger specification file // GetSwagger returns the content of the embedded swagger specification file

4
internal/swagger/api.go Normal file

@ -0,0 +1,4 @@
package swagger
//go:generate oapi-codegen --config api.yaml ../../openapi.yaml
//go:generate oapi-codegen --config models.yaml ../../openapi.yaml

@ -0,0 +1,6 @@
output: api.gen.go
package: swagger
generate:
echo-server: true
models: false
embedded-spec: true

@ -1,3 +0,0 @@
package swagger
//go:generate oapi-codegen --config oapi-codegen.yaml ../../openapi.yaml

@ -0,0 +1,139 @@
// Package swagger provides primitives to interact with the openapi HTTP API.
//
// Code generated by github.com/deepmap/oapi-codegen version v1.12.4 DO NOT EDIT.
package swagger
import (
"time"
)
const (
BearerScopes = "Bearer.Scopes"
)
// Defines values for HistoryType.
const (
BuyCart HistoryType = "buyCart"
DeclinedPayment HistoryType = "declinedPayment"
SubsriptionEnd HistoryType = "subsriptionEnd"
SuccessfulPayment HistoryType = "successfulPayment"
TimeoutPayment HistoryType = "timeoutPayment"
)
// Account defines model for Account.
type Account struct {
Id string `json:"_id"`
Cart []string `json:"cart"`
CreatedAt time.Time `json:"createdAt"`
Deleted bool `json:"deleted"`
DeletedAt *time.Time `json:"deletedAt,omitempty"`
UpdatedAt time.Time `json:"updatedAt"`
UserId string `json:"userId"`
Wallet Wallet `json:"wallet"`
}
// Error defines model for Error.
type Error struct {
Message string `json:"message"`
StatusCode *int64 `json:"statusCode,omitempty"`
}
// History defines model for History.
type History struct {
Comment *string `json:"comment,omitempty"`
CreatedAt *time.Time `json:"createdAt,omitempty"`
Deleted *bool `json:"deleted,omitempty"`
DeletedAt *time.Time `json:"deletedAt,omitempty"`
Id *string `json:"id,omitempty"`
// Subject Я пока не могу предположить, какие будут фильтры по истории, поэтому предлагаю в это поле просто класть строку с json. ибо для каждого типа записи она своя.
Subject *string `json:"subject,omitempty"`
Type *HistoryType `json:"type,omitempty"`
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
UserId *string `json:"userId,omitempty"`
}
// HistoryType defines model for History.Type.
type HistoryType string
// Wallet defines model for Wallet.
type Wallet struct {
Cash *int64 `json:"cash,omitempty"`
Currency *string `json:"currency,omitempty"`
// Money деньги на счету в копейках. Чтобы при перессчётах не возникало денег изниоткуда. фиксируемся к одной валюте, она будет внутренней, никому её не покажем
Money *int64 `json:"money,omitempty"`
}
// PaginationAccountsParams defines parameters for PaginationAccounts.
type PaginationAccountsParams struct {
// Page Номер страницы, начиная с 1
Page *int `form:"page,omitempty" json:"page,omitempty"`
// Limit размер страницы
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
}
// RemoveFromCartParams defines parameters for RemoveFromCart.
type RemoveFromCartParams struct {
Id string `form:"id" json:"id"`
}
// Add2cartJSONBody defines parameters for Add2cart.
type Add2cartJSONBody struct {
Id *string `json:"id,omitempty"`
}
// PayCartJSONBody defines parameters for PayCart.
type PayCartJSONBody struct {
// UserId ID для того, чтобы указать сервису оплаты, какой юзер оплатил
UserId *string `json:"userId,omitempty"`
}
// UpdateCurrenciesJSONBody defines parameters for UpdateCurrencies.
type UpdateCurrenciesJSONBody = []string
// GetHistoryParams defines parameters for GetHistory.
type GetHistoryParams struct {
// P Номер страницы, начиная с 1
P *int `form:"p,omitempty" json:"p,omitempty"`
// S Размер страницы
S *int `form:"s,omitempty" json:"s,omitempty"`
}
// RequestMoneyParams defines parameters for RequestMoney.
type RequestMoneyParams struct {
// Cash Номер страницы, начиная с 1
Cash int `form:"cash" json:"cash"`
}
// ChangeCurrencyJSONBody defines parameters for ChangeCurrency.
type ChangeCurrencyJSONBody struct {
Currency *string `json:"currency,omitempty"`
}
// PutMoneyJSONBody defines parameters for PutMoney.
type PutMoneyJSONBody struct {
Cash *int `json:"cash,omitempty"`
Currency *string `json:"currency,omitempty"`
UserId *string `json:"userId,omitempty"`
}
// Add2cartJSONRequestBody defines body for Add2cart for application/json ContentType.
type Add2cartJSONRequestBody Add2cartJSONBody
// PayCartJSONRequestBody defines body for PayCart for application/json ContentType.
type PayCartJSONRequestBody PayCartJSONBody
// UpdateCurrenciesJSONRequestBody defines body for UpdateCurrencies for application/json ContentType.
type UpdateCurrenciesJSONRequestBody = UpdateCurrenciesJSONBody
// Add2historyJSONRequestBody defines body for Add2history for application/json ContentType.
type Add2historyJSONRequestBody = History
// ChangeCurrencyJSONRequestBody defines body for ChangeCurrency for application/json ContentType.
type ChangeCurrencyJSONRequestBody ChangeCurrencyJSONBody
// PutMoneyJSONRequestBody defines body for PutMoney for application/json ContentType.
type PutMoneyJSONRequestBody PutMoneyJSONBody

@ -0,0 +1,4 @@
output: models.gen.go
package: swagger
generate:
models: true

@ -1,7 +0,0 @@
output: server.gen.go
package: swagger
generate:
# other servers are available!
echo-server: true
models: true
embedded-spec: true

@ -4,6 +4,7 @@ info:
description: |- description: |-
Область ответственности сервиса - предоставление пользователю функционала корзины и кошелька. Область ответственности сервиса - предоставление пользователю функционала корзины и кошелька.
version: 1.0.0 version: 1.0.0
tags: tags:
- name: account - name: account
description: аккаунт description: аккаунт
@ -15,14 +16,17 @@ tags:
description: кошелёк description: кошелёк
- name: history - name: history
description: история description: история
paths: paths:
/account: /account:
get: get:
tags: tags:
- account - account
summary: Получение текущего аккаунта юзера summary: Получение текущего аккаунта юзера
description: используется при заходе юзера в систему. Айдишник юзера получает из токена, который передаётся в заголовке authorization description: Используется при заходе юзера в систему. Айдишник юзера получает из токена, который передаётся в заголовке authorization
operationId: getAccount operationId: getAccount
security:
- Bearer: []
responses: responses:
'200': '200':
description: успешное получение description: успешное получение
@ -32,34 +36,59 @@ paths:
$ref: '#/components/schemas/Account' $ref: '#/components/schemas/Account'
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404': '404':
description: Такого пользователя нет description: Такого пользователя нет
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post: post:
tags: tags:
- account - account
summary: создать новый аккаунт summary: Создать новый аккаунт
description: создаёт новый аккаунт для юзера, если такого ещё не было description: Создаёт новый аккаунт для юзера, если такого ещё не было
operationId: addAccount operationId: addAccount
security:
- Bearer: []
responses: responses:
'201': '200':
description: успешное созание аккаунта description: успешное создание аккаунта
content: content:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Account' $ref: '#/components/schemas/Account'
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete: delete:
tags: tags:
- account - account
summary: удалить собственный аккаунт summary: удалить собственный аккаунт
description: помечает аккаунт удалённым description: помечает аккаунт удалённым
operationId: deleteAccount operationId: deleteAccount
security:
- Bearer: []
responses: responses:
'200': '200':
description: успешное удаление аккаунта description: успешное удаление аккаунта
content:
application/json:
schema:
$ref: '#/components/schemas/Account'
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/accounts: /accounts:
get: get:
tags: tags:
@ -68,22 +97,22 @@ paths:
description: получает список аккаунтов на указанной странице + общее количество аккаунтов description: получает список аккаунтов на указанной странице + общее количество аккаунтов
operationId: paginationAccounts operationId: paginationAccounts
parameters: parameters:
- name: p - name: page
in: query in: query
description: Номер страницы, начиная с 0 description: Номер страницы, начиная с 1
required: false required: false
explode: false explode: false
schema: schema:
type: integer type: integer
default: 0 default: 1
- name: s - name: limit
in: query in: query
description: размер страницы description: размер страницы
required: false required: false
explode: false explode: false
schema: schema:
type: integer type: integer
default: 10 default: 100
responses: responses:
'200': '200':
description: успешное получение страницы аккаунтов description: успешное получение страницы аккаунтов
@ -92,60 +121,84 @@ paths:
schema: schema:
type: object type: object
properties: properties:
count: totalPages:
type: integer type: integer
example: 11 example: 11
items: accounts:
type: array type: array
items: items:
$ref: "#/components/schemas/Account" $ref: "#/components/schemas/Account"
'401':
description: Неавторизован
/account/{accountId}: /account/{accountId}:
get: get:
tags: tags:
- account - account
summary: получить аккаунт по айди summary: Получить аккаунт по ID
description: метод необходимый в основном только менеджерам, для получения данных о клиенте description: Метод необходимый в основном только менеджерам, для получения данных о клиенте
security:
- Bearer: []
operationId: getDirectAccount operationId: getDirectAccount
parameters: parameters:
- name: accountId - name: accountId
in: path in: path
description: айдишник аккаунта description: id аккаунта
required: true required: true
schema: schema:
type: string type: string
responses: responses:
'200': '200':
description: успешное получение аккаунта description: Успешное получение аккаунта
content: content:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Account' $ref: '#/components/schemas/Account'
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404': '404':
description: Нет такого пользователя description: Нет такого пользователя
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete: delete:
tags: tags:
- account - account
summary: удалить аккаунт по айди summary: Удалить аккаунт по айди
description: метод необходимый в основном только менеджерам, для удаления клиента description: Метод необходимый в основном только менеджерам, для удаления клиента
operationId: deleteDirectAccount operationId: deleteDirectAccount
security:
- Bearer: []
parameters: parameters:
- name: accountId - name: accountId
in: path in: path
description: айдишник аккаунта description: ID аккаунта
required: true required: true
schema: schema:
type: string type: string
responses: responses:
'200': '200':
description: успешное удаление аккаунта description: Успешное удаление аккаунта
content:
application/json:
schema:
$ref: '#/components/schemas/Account'
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404': '404':
description: Нет такого пользователя description: Нет такого пользователя
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/currencies: /currencies:
get: get:
tags: tags:
@ -165,7 +218,7 @@ paths:
- "CAD" - "CAD"
items: items:
type: string type: string
patch: put:
tags: tags:
- currency - currency
summary: обновляет список одобренных валют summary: обновляет список одобренных валют
@ -182,15 +235,30 @@ paths:
items: items:
type: string type: string
responses: responses:
'200':
description: успешное обновление списка валют
content:
application/json:
schema:
type: array
example:
- "RUB"
- "USD"
- "CAD"
items:
type: string
'401': '401':
description: Uanuthorized description: Uanuthorized
/cart: /cart:
put: patch:
tags: tags:
- cart - cart
summary: добавляем в корзину тариф summary: Добавляем в корзину тариф
description: 'необходимо проверить, что такой тариф существует' description: Необходимо проверить, что такой тариф существует
operationId: add2cart operationId: add2cart
security:
- Bearer: []
requestBody: requestBody:
content: content:
application/json: application/json:
@ -202,16 +270,30 @@ paths:
example: "807f1f77bcf81cd799439011" example: "807f1f77bcf81cd799439011"
responses: responses:
'200': '200':
description: добавлено в корзину description: Добавлено в корзину
content:
application/json:
schema:
$ref: '#/components/schemas/Account'
'401': '401':
description: неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404': '404':
description: не найден такой тариф description: Не найден такой тариф
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete: delete:
tags: tags:
- cart - cart
summary: удаляем из корзины тариф summary: Удаляем из корзины тариф
operationId: removeFromCart operationId: removeFromCart
security:
- Bearer: []
parameters: parameters:
- name: id - name: id
in: query in: query
@ -221,30 +303,50 @@ paths:
example: "807f1f77bcf81cd799439011" example: "807f1f77bcf81cd799439011"
responses: responses:
'200': '200':
description: удалено из корзины description: Удалено из корзины
content:
application/json:
schema:
$ref: '#/components/schemas/Account'
'401': '401':
description: неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404': '404':
description: не найден такой тариф description: Не найден такой тариф
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/cart/pay: /cart/pay:
post: post:
tags: tags:
- cart - cart
summary: оплатить козину summary: оплатить козину
description: "- очевидно нужен воркер или очередь(место где можно потрогать кафку), которая будет слать запросы в конечные сервисы для добавления привилегий в аккаунт пользователя\n
- в случае если денег в кошельке достаточно - отправить в воркер или очередь задачи на разослать конкретным сервисам добавление привилегий\n
- если денег недостаточно, получить ссылку на оплату у сервиса платёжки и вернуть её. в случае оплаты, повторить вызов этого метода\n
- очистить корзину"
operationId: payCart operationId: payCart
security:
- Bearer: []
description: >-
- Очевидно нужен воркер или очередь(место где можно потрогать кафку), которая будет слать запросы в конечные сервисы для добавления привилегий в аккаунт пользователя
- В случае если денег в кошельке достаточно - отправить в воркер или очередь задачи на разослать конкретным сервисам добавление привилегий
- Если денег недостаточно, получить ссылку на оплату у сервиса платёжки и вернуть её. в случае оплаты, повторить вызов этого метода
- Очистить корзину
requestBody: requestBody:
content: content:
application/json: application/json:
schema: schema:
type: object type: object
properties: properties:
id: userId:
type: string type: string
description: айдишник для того, чтобы указать сервису оплаты, какой юзер оплатил description: ID для того, чтобы указать сервису оплаты, какой юзер оплатил
example: "807f1f77bcf81cd799439011" example: "807f1f77bcf81cd799439011"
responses: responses:
'200': '200':
@ -255,16 +357,28 @@ paths:
$ref: '#/components/schemas/Account' $ref: '#/components/schemas/Account'
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/wallet: /wallet:
patch: patch:
tags: tags:
- wallet - wallet
summary: изменить валюту кошелька summary: Изменить валюту кошелька
description: "при запросе:\n
- отвалидировать, что такая валюта одобрена \n
- получить данные из сервиса cbrf(выдам задачу на него чуть позднее)\n
- перевести валюту кошелька в нвоую валюту. кошелёк нарочно целочисленный, чтобы не было претензий к точности с плавающей точкой, поэтому, например долларовый счёт считается в центах"
operationId: changeCurrency operationId: changeCurrency
description: >-
При запросе необходимо:
- Отвалидировать, что такая валюта одобрена
- Получить данные из сервиса cbrf(выдам задачу на него чуть позднее)
- Перевести валюту кошелька в нвоую валюту. кошелёк нарочно целочисленный, чтобы не было претензий к точности с плавающей точкой, поэтому, например долларовый счёт считается в центах
security:
- Bearer: []
requestBody: requestBody:
content: content:
application/json: application/json:
@ -276,21 +390,37 @@ paths:
example: "USD" example: "USD"
responses: responses:
'200': '200':
description: успешная смена валюты кошелька description: Успешная смена валюты кошелька
content: content:
application/json: application/json:
schema: schema:
$ref: "#/components/schemas/Account" $ref: "#/components/schemas/Account"
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
'400': '400':
description: Такая валюта не одобрена description: Такая валюта не одобрена
put: content:
application/json:
schema:
$ref: "#/components/schemas/Error"
'404':
description: Пользователь не найден
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
tags: tags:
- wallet - wallet
summary: зачислить деньги на кошелёк summary: Зачислить деньги на кошелёк
description: "прибавляем полученное значение к cash и при необходимости приводим к валюте кошелька" description: "Прибавляем полученное значение к cash и при необходимости приводим к валюте кошелька"
operationId: putMoney operationId: putMoney
security:
- Bearer: []
requestBody: requestBody:
content: content:
application/json: application/json:
@ -303,7 +433,7 @@ paths:
currency: currency:
type: string type: string
example: "USD" example: "USD"
id: userId:
type: string type: string
example: "807f1f77bcf81cd799439011" example: "807f1f77bcf81cd799439011"
responses: responses:
@ -315,25 +445,39 @@ paths:
$ref: "#/components/schemas/Account" $ref: "#/components/schemas/Account"
'400': '400':
description: Такая валюта не одобрена description: Такая валюта не одобрена
post:
tags:
- wallet
summary: запрос на получение ссылки на оплату
description: "- формируем запрос к сервису оплаты, с необходимыми постбэками\n
- получаем ответ от сервиса оплаты с ссылкой на оплату, которую надо передать пользователю"
operationId: requestMoney
requestBody:
content: content:
application/json: application/json:
schema: schema:
type: object $ref: "#/components/schemas/Error"
properties: '404':
cash: description: Аккаунт не найден
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
get:
tags:
- wallet
summary: Запрос на получение ссылки на оплату
operationId: requestMoney
description: >-
- Формируем запрос к сервису оплаты, с необходимыми постбэками
- Получаем ответ от сервиса оплаты с ссылкой на оплату, которую надо передать пользователю
security:
- Bearer: []
parameters:
- name: cash
in: query
description: Номер страницы, начиная с 1
required: true
schema:
type: integer type: integer
example: 10000 default: 10000
responses: responses:
'200': '200':
description: успешный зпрос денег description: Успешный запрос денег
content: content:
application/json: application/json:
schema: schema:
@ -343,17 +487,24 @@ paths:
type: string type: string
example: "https://google.ru" example: "https://google.ru"
'500': '500':
description: сервис оплаты вернул ошибку description: Сервис оплаты вернул ошибку
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/history: /history:
get: get:
tags: tags:
- history - history
summary: получение лога событий связанных с аккаунтом summary: Получение лога событий связанных с аккаунтом
operationId: getHistory operationId: getHistory
security:
- Bearer: []
parameters: parameters:
- name: p - name: p
in: query in: query
description: Номер страницы, начиная с 0 description: Номер страницы, начиная с 1
required: false required: false
explode: false explode: false
schema: schema:
@ -361,46 +512,66 @@ paths:
default: 0 default: 0
- name: s - name: s
in: query in: query
description: размер страницы description: Размер страницы
required: false required: false
explode: false explode: false
schema: schema:
type: integer type: integer
default: 10 default: 100
responses: responses:
'200': '200':
description: successful operation description: Успешное получение событий
content: content:
application/json: application/json:
schema: schema:
type: object type: object
properties: properties:
count: totalPages:
type: integer type: integer
example: 11 example: 11
items: records:
type: array type: array
items: items:
$ref: '#/components/schemas/Record' $ref: '#/components/schemas/History'
'401': '401':
description: Неавторизован description: Неавторизован
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post: post:
tags: tags:
- history - history
summary: публикация лога в истории summary: Публикация лога в истории
operationId: add2history operationId: add2history
security:
- Bearer: []
requestBody: requestBody:
content: content:
application/json: application/json:
schema: schema:
$ref: "#/components/schemas/Record" $ref: "#/components/schemas/History"
responses: responses:
'200': '200':
description: successful operation description: Успешная публикация лога
content:
application/json:
schema:
$ref: "#/components/schemas/History"
'500':
description: Ошибка при публикации
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components: components:
schemas: schemas:
Account: Account:
type: object type: object
required: [_id, userId, cart, wallet, deleted, createdAt, updatedAt]
properties: properties:
_id: _id:
type: string type: string
@ -409,12 +580,27 @@ components:
type: string type: string
example: "807f1f77bcf81cd799439011" example: "807f1f77bcf81cd799439011"
cart: cart:
$ref: "#/components/schemas/Cart" type: array
items:
type: string
example:
- "807f1f77bcf81cd799439011"
- "807f1f77bcf81cd799439012"
wallet: wallet:
$ref: "#/components/schemas/Wallet" $ref: "#/components/schemas/Wallet"
isDeleted: deleted:
type: boolean type: boolean
example: false example: false
createdAt:
type: string
format: "date-time"
updatedAt:
type: string
format: "date-time"
deletedAt:
type: string
format: "date-time"
Wallet: Wallet:
type: object type: object
properties: properties:
@ -429,16 +615,9 @@ components:
type: integer type: integer
format: int64 format: int64
description: деньги на счету в копейках. Чтобы при перессчётах не возникало денег изниоткуда. фиксируемся к одной валюте, она будет внутренней, никому её не покажем description: деньги на счету в копейках. Чтобы при перессчётах не возникало денег изниоткуда. фиксируемся к одной валюте, она будет внутренней, никому её не покажем
example: 10701 example: 10701.60
Cart:
type: array History:
items:
type: string
example:
- "807f1f77bcf81cd799439011"
- "807f1f77bcf81cd799439011"
- "807f1f77bcf81cd799439011"
Record:
type: object type: object
properties: properties:
id: id:
@ -451,13 +630,47 @@ components:
type: string type: string
enum: ["successfulPayment", "declinedPayment", "timeoutPayment", "buyCart", "subsriptionEnd"] enum: ["successfulPayment", "declinedPayment", "timeoutPayment", "buyCart", "subsriptionEnd"]
example: "successfulPayment" example: "successfulPayment"
deleted:
type: boolean
example: false
createdAt: createdAt:
type: string type: string
format: date-time format: "date-time"
updatedAt:
type: string
format: "date-time"
deletedAt:
type: string
format: "date-time"
comment: comment:
type: string type: string
example: "я это сделал потому что 42" example: "я это сделал потому что 42"
subject: subject:
type: string type: string
description: я пока не могу предположить, какие будут фильтры по истории, поэтому предлагаю в это поле просто класть строку с json. ибо для каждого типа записи она своя. description: >-
Я пока не могу предположить, какие будут фильтры по истории, поэтому
предлагаю в это поле просто класть строку с json. ибо для каждого типа
записи она своя.
example: {"tariffs":["807f1f77bcf81cd799439011","807f1f77bcf81cd799439011"]} example: {"tariffs":["807f1f77bcf81cd799439011","807f1f77bcf81cd799439011"]}
Error:
type: object
required:
- code
- message
properties:
statusCode:
type: integer
format: int64
example: 404
message:
type: string
example: user not found
securitySchemes:
Bearer: # arbitrary name for the security scheme
type: http
scheme: bearer
bearerFormat: JWT
description: >-
Enter the token with the `Bearer: ` prefix, e.g. "Bearer abcde12345".