first
This commit is contained in:
commit
d40e30944b
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
t
|
213
ent/client.go
Normal file
213
ent/client.go
Normal file
@ -0,0 +1,213 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"t/ent/migrate"
|
||||
|
||||
"t/ent/users"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Client is the client that holds all ent builders.
|
||||
type Client struct {
|
||||
config
|
||||
// Schema is the client for creating, migrating and dropping schema.
|
||||
Schema *migrate.Schema
|
||||
// Users is the client for interacting with the Users builders.
|
||||
Users *UsersClient
|
||||
}
|
||||
|
||||
// NewClient creates a new client configured with the given options.
|
||||
func NewClient(opts ...Option) *Client {
|
||||
cfg := config{log: log.Println, hooks: &hooks{}}
|
||||
cfg.options(opts...)
|
||||
client := &Client{config: cfg}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
func (c *Client) init() {
|
||||
c.Schema = migrate.NewSchema(c.driver)
|
||||
c.Users = NewUsersClient(c.config)
|
||||
}
|
||||
|
||||
// Open opens a database/sql.DB specified by the driver name and
|
||||
// the data source name, and returns a new client attached to it.
|
||||
// Optional parameters can be added for configuring the client.
|
||||
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
|
||||
switch driverName {
|
||||
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
|
||||
drv, err := sql.Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewClient(append(options, Driver(drv))...), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported driver: %q", driverName)
|
||||
}
|
||||
}
|
||||
|
||||
// Tx returns a new transactional client. The provided context
|
||||
// is used until the transaction is committed or rolled back.
|
||||
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
|
||||
if _, ok := c.driver.(*txDriver); ok {
|
||||
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
|
||||
}
|
||||
tx, err := newTx(ctx, c.driver)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = tx
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
Users: NewUsersClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// BeginTx returns a transactional client with specified options.
|
||||
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
|
||||
if _, ok := c.driver.(*txDriver); ok {
|
||||
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
|
||||
}
|
||||
tx, err := c.driver.(interface {
|
||||
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
|
||||
}).BeginTx(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = &txDriver{tx: tx, drv: c.driver}
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
Users: NewUsersClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
|
||||
//
|
||||
// client.Debug().
|
||||
// Users.
|
||||
// Query().
|
||||
// Count(ctx)
|
||||
//
|
||||
func (c *Client) Debug() *Client {
|
||||
if c.debug {
|
||||
return c
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = dialect.Debug(c.driver, c.log)
|
||||
client := &Client{config: cfg}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
// Close closes the database connection and prevents new queries from starting.
|
||||
func (c *Client) Close() error {
|
||||
return c.driver.Close()
|
||||
}
|
||||
|
||||
// Use adds the mutation hooks to all the entity clients.
|
||||
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
|
||||
func (c *Client) Use(hooks ...Hook) {
|
||||
c.Users.Use(hooks...)
|
||||
}
|
||||
|
||||
// UsersClient is a client for the Users schema.
|
||||
type UsersClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewUsersClient returns a client for the Users from the given config.
|
||||
func NewUsersClient(c config) *UsersClient {
|
||||
return &UsersClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `users.Hooks(f(g(h())))`.
|
||||
func (c *UsersClient) Use(hooks ...Hook) {
|
||||
c.hooks.Users = append(c.hooks.Users, hooks...)
|
||||
}
|
||||
|
||||
// Create returns a create builder for Users.
|
||||
func (c *UsersClient) Create() *UsersCreate {
|
||||
mutation := newUsersMutation(c.config, OpCreate)
|
||||
return &UsersCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of Users entities.
|
||||
func (c *UsersClient) CreateBulk(builders ...*UsersCreate) *UsersCreateBulk {
|
||||
return &UsersCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for Users.
|
||||
func (c *UsersClient) Update() *UsersUpdate {
|
||||
mutation := newUsersMutation(c.config, OpUpdate)
|
||||
return &UsersUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *UsersClient) UpdateOne(u *Users) *UsersUpdateOne {
|
||||
mutation := newUsersMutation(c.config, OpUpdateOne, withUsers(u))
|
||||
return &UsersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *UsersClient) UpdateOneID(id int) *UsersUpdateOne {
|
||||
mutation := newUsersMutation(c.config, OpUpdateOne, withUsersID(id))
|
||||
return &UsersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for Users.
|
||||
func (c *UsersClient) Delete() *UsersDelete {
|
||||
mutation := newUsersMutation(c.config, OpDelete)
|
||||
return &UsersDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a delete builder for the given entity.
|
||||
func (c *UsersClient) DeleteOne(u *Users) *UsersDeleteOne {
|
||||
return c.DeleteOneID(u.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a delete builder for the given id.
|
||||
func (c *UsersClient) DeleteOneID(id int) *UsersDeleteOne {
|
||||
builder := c.Delete().Where(users.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &UsersDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for Users.
|
||||
func (c *UsersClient) Query() *UsersQuery {
|
||||
return &UsersQuery{
|
||||
config: c.config,
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a Users entity by its id.
|
||||
func (c *UsersClient) Get(ctx context.Context, id int) (*Users, error) {
|
||||
return c.Query().Where(users.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *UsersClient) GetX(ctx context.Context, id int) *Users {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *UsersClient) Hooks() []Hook {
|
||||
return c.hooks.Users
|
||||
}
|
59
ent/config.go
Normal file
59
ent/config.go
Normal file
@ -0,0 +1,59 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect"
|
||||
)
|
||||
|
||||
// Option function to configure the client.
|
||||
type Option func(*config)
|
||||
|
||||
// Config is the configuration for the client and its builder.
|
||||
type config struct {
|
||||
// driver used for executing database requests.
|
||||
driver dialect.Driver
|
||||
// debug enable a debug logging.
|
||||
debug bool
|
||||
// log used for logging on debug mode.
|
||||
log func(...interface{})
|
||||
// hooks to execute on mutations.
|
||||
hooks *hooks
|
||||
}
|
||||
|
||||
// hooks per client, for fast access.
|
||||
type hooks struct {
|
||||
Users []ent.Hook
|
||||
}
|
||||
|
||||
// Options applies the options on the config object.
|
||||
func (c *config) options(opts ...Option) {
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
if c.debug {
|
||||
c.driver = dialect.Debug(c.driver, c.log)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug enables debug logging on the ent.Driver.
|
||||
func Debug() Option {
|
||||
return func(c *config) {
|
||||
c.debug = true
|
||||
}
|
||||
}
|
||||
|
||||
// Log sets the logging function for debug mode.
|
||||
func Log(fn func(...interface{})) Option {
|
||||
return func(c *config) {
|
||||
c.log = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Driver configures the client driver.
|
||||
func Driver(driver dialect.Driver) Option {
|
||||
return func(c *config) {
|
||||
c.driver = driver
|
||||
}
|
||||
}
|
33
ent/context.go
Normal file
33
ent/context.go
Normal file
@ -0,0 +1,33 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type clientCtxKey struct{}
|
||||
|
||||
// FromContext returns a Client stored inside a context, or nil if there isn't one.
|
||||
func FromContext(ctx context.Context) *Client {
|
||||
c, _ := ctx.Value(clientCtxKey{}).(*Client)
|
||||
return c
|
||||
}
|
||||
|
||||
// NewContext returns a new context with the given Client attached.
|
||||
func NewContext(parent context.Context, c *Client) context.Context {
|
||||
return context.WithValue(parent, clientCtxKey{}, c)
|
||||
}
|
||||
|
||||
type txCtxKey struct{}
|
||||
|
||||
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
|
||||
func TxFromContext(ctx context.Context) *Tx {
|
||||
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
|
||||
return tx
|
||||
}
|
||||
|
||||
// NewTxContext returns a new context with the given Tx attached.
|
||||
func NewTxContext(parent context.Context, tx *Tx) context.Context {
|
||||
return context.WithValue(parent, txCtxKey{}, tx)
|
||||
}
|
259
ent/ent.go
Normal file
259
ent/ent.go
Normal file
@ -0,0 +1,259 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"t/ent/users"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// ent aliases to avoid import conflicts in user's code.
|
||||
type (
|
||||
Op = ent.Op
|
||||
Hook = ent.Hook
|
||||
Value = ent.Value
|
||||
Query = ent.Query
|
||||
Policy = ent.Policy
|
||||
Mutator = ent.Mutator
|
||||
Mutation = ent.Mutation
|
||||
MutateFunc = ent.MutateFunc
|
||||
)
|
||||
|
||||
// OrderFunc applies an ordering on the sql selector.
|
||||
type OrderFunc func(*sql.Selector)
|
||||
|
||||
// columnChecker returns a function indicates if the column exists in the given column.
|
||||
func columnChecker(table string) func(string) error {
|
||||
checks := map[string]func(string) bool{
|
||||
users.Table: users.ValidColumn,
|
||||
}
|
||||
check, ok := checks[table]
|
||||
if !ok {
|
||||
return func(string) error {
|
||||
return fmt.Errorf("unknown table %q", table)
|
||||
}
|
||||
}
|
||||
return func(column string) error {
|
||||
if !check(column) {
|
||||
return fmt.Errorf("unknown column %q for table %q", column, table)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Asc applies the given fields in ASC order.
|
||||
func Asc(fields ...string) OrderFunc {
|
||||
return func(s *sql.Selector) {
|
||||
check := columnChecker(s.TableName())
|
||||
for _, f := range fields {
|
||||
if err := check(f); err != nil {
|
||||
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
|
||||
}
|
||||
s.OrderBy(sql.Asc(s.C(f)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Desc applies the given fields in DESC order.
|
||||
func Desc(fields ...string) OrderFunc {
|
||||
return func(s *sql.Selector) {
|
||||
check := columnChecker(s.TableName())
|
||||
for _, f := range fields {
|
||||
if err := check(f); err != nil {
|
||||
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
|
||||
}
|
||||
s.OrderBy(sql.Desc(s.C(f)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
|
||||
type AggregateFunc func(*sql.Selector) string
|
||||
|
||||
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
|
||||
//
|
||||
// GroupBy(field1, field2).
|
||||
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func As(fn AggregateFunc, end string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
return sql.As(fn(s), end)
|
||||
}
|
||||
}
|
||||
|
||||
// Count applies the "count" aggregation function on each group.
|
||||
func Count() AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
return sql.Count("*")
|
||||
}
|
||||
}
|
||||
|
||||
// Max applies the "max" aggregation function on the given field of each group.
|
||||
func Max(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Max(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Mean applies the "mean" aggregation function on the given field of each group.
|
||||
func Mean(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Avg(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Min applies the "min" aggregation function on the given field of each group.
|
||||
func Min(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Min(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Sum applies the "sum" aggregation function on the given field of each group.
|
||||
func Sum(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Sum(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// ValidationError returns when validating a field or edge fails.
|
||||
type ValidationError struct {
|
||||
Name string // Field or edge name.
|
||||
err error
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *ValidationError) Error() string {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
// Unwrap implements the errors.Wrapper interface.
|
||||
func (e *ValidationError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
// IsValidationError returns a boolean indicating whether the error is a validation error.
|
||||
func IsValidationError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *ValidationError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
|
||||
type NotFoundError struct {
|
||||
label string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotFoundError) Error() string {
|
||||
return "ent: " + e.label + " not found"
|
||||
}
|
||||
|
||||
// IsNotFound returns a boolean indicating whether the error is a not found error.
|
||||
func IsNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotFoundError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// MaskNotFound masks not found error.
|
||||
func MaskNotFound(err error) error {
|
||||
if IsNotFound(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
|
||||
type NotSingularError struct {
|
||||
label string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotSingularError) Error() string {
|
||||
return "ent: " + e.label + " not singular"
|
||||
}
|
||||
|
||||
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
|
||||
func IsNotSingular(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotSingularError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// NotLoadedError returns when trying to get a node that was not loaded by the query.
|
||||
type NotLoadedError struct {
|
||||
edge string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotLoadedError) Error() string {
|
||||
return "ent: " + e.edge + " edge was not loaded"
|
||||
}
|
||||
|
||||
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
|
||||
func IsNotLoaded(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotLoadedError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// ConstraintError returns when trying to create/update one or more entities and
|
||||
// one or more of their constraints failed. For example, violation of edge or
|
||||
// field uniqueness.
|
||||
type ConstraintError struct {
|
||||
msg string
|
||||
wrap error
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e ConstraintError) Error() string {
|
||||
return "ent: constraint failed: " + e.msg
|
||||
}
|
||||
|
||||
// Unwrap implements the errors.Wrapper interface.
|
||||
func (e *ConstraintError) Unwrap() error {
|
||||
return e.wrap
|
||||
}
|
||||
|
||||
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
|
||||
func IsConstraintError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *ConstraintError
|
||||
return errors.As(err, &e)
|
||||
}
|
85
ent/entc.go
Normal file
85
ent/entc.go
Normal file
@ -0,0 +1,85 @@
|
||||
//go:build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"entgo.io/contrib/entoas"
|
||||
"entgo.io/ent/entc"
|
||||
"entgo.io/ent/entc/gen"
|
||||
"github.com/ariga/ogent"
|
||||
"github.com/ogen-go/ogen"
|
||||
)
|
||||
|
||||
func main() {
|
||||
spec := new(ogen.Spec)
|
||||
|
||||
//oas, err := entoas.NewExtension(entoas.Spec(spec))
|
||||
oas, err := entoas.NewExtension(
|
||||
entoas.Spec(spec),
|
||||
entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
|
||||
spec.AddPathItem("/users/{id}/start", ogen.NewPathItem().
|
||||
SetDescription("Start an draw as done").
|
||||
SetPatch(ogen.NewOperation().
|
||||
SetOperationID("drawStart").
|
||||
SetSummary("Draws a card item as done.").
|
||||
AddTags("Users").
|
||||
AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
|
||||
).
|
||||
AddParameters(ogen.NewParameter().
|
||||
InPath().
|
||||
SetName("id").
|
||||
SetRequired(true).
|
||||
SetSchema(ogen.Int()),
|
||||
),
|
||||
)
|
||||
return nil
|
||||
}),
|
||||
|
||||
// entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
|
||||
// spec.AddPathItem(
|
||||
// "/syui",
|
||||
// ogen.NewPathItem().
|
||||
// SetGet(
|
||||
// ogen.NewOperation().
|
||||
// SetOperationID("customReadUser").
|
||||
//
|
||||
// AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
|
||||
// ),
|
||||
// )
|
||||
// return nil
|
||||
// }),
|
||||
entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
|
||||
spec.AddPathItem("/users/{id}/d", ogen.NewPathItem().
|
||||
SetDescription("Start an draw as done").
|
||||
SetPut(ogen.NewOperation().
|
||||
SetOperationID("drawDone").
|
||||
SetSummary("Draws a card item as done.").
|
||||
AddTags("Users").
|
||||
AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
|
||||
//AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done").SetSchema("test")),
|
||||
).
|
||||
AddParameters(ogen.NewParameter().
|
||||
InPath().
|
||||
SetName("id").
|
||||
SetRequired(true).
|
||||
SetSchema(ogen.Int()),
|
||||
),
|
||||
)
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("creating entoas extension: %v", err)
|
||||
}
|
||||
ogent, err := ogent.NewExtension(spec)
|
||||
if err != nil {
|
||||
log.Fatalf("creating ogent extension: %v", err)
|
||||
}
|
||||
err = entc.Generate("./schema", &gen.Config{}, entc.Extensions(ogent, oas))
|
||||
if err != nil {
|
||||
log.Fatalf("running ent codegen: %v", err)
|
||||
}
|
||||
}
|
77
ent/enttest/enttest.go
Normal file
77
ent/enttest/enttest.go
Normal file
@ -0,0 +1,77 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package enttest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"t/ent"
|
||||
// required by schema hooks.
|
||||
_ "t/ent/runtime"
|
||||
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
)
|
||||
|
||||
type (
|
||||
// TestingT is the interface that is shared between
|
||||
// testing.T and testing.B and used by enttest.
|
||||
TestingT interface {
|
||||
FailNow()
|
||||
Error(...interface{})
|
||||
}
|
||||
|
||||
// Option configures client creation.
|
||||
Option func(*options)
|
||||
|
||||
options struct {
|
||||
opts []ent.Option
|
||||
migrateOpts []schema.MigrateOption
|
||||
}
|
||||
)
|
||||
|
||||
// WithOptions forwards options to client creation.
|
||||
func WithOptions(opts ...ent.Option) Option {
|
||||
return func(o *options) {
|
||||
o.opts = append(o.opts, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithMigrateOptions forwards options to auto migration.
|
||||
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
|
||||
return func(o *options) {
|
||||
o.migrateOpts = append(o.migrateOpts, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
func newOptions(opts []Option) *options {
|
||||
o := &options{}
|
||||
for _, opt := range opts {
|
||||
opt(o)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
// Open calls ent.Open and auto-run migration.
|
||||
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
|
||||
o := newOptions(opts)
|
||||
c, err := ent.Open(driverName, dataSourceName, o.opts...)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// NewClient calls ent.NewClient and auto-run migration.
|
||||
func NewClient(t TestingT, opts ...Option) *ent.Client {
|
||||
o := newOptions(opts)
|
||||
c := ent.NewClient(o.opts...)
|
||||
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
return c
|
||||
}
|
4
ent/generate.go
Normal file
4
ent/generate.go
Normal file
@ -0,0 +1,4 @@
|
||||
package ent
|
||||
|
||||
//go:generate go run -mod=mod entc.go
|
||||
|
203
ent/hook/hook.go
Normal file
203
ent/hook/hook.go
Normal file
@ -0,0 +1,203 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package hook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"t/ent"
|
||||
)
|
||||
|
||||
// The UsersFunc type is an adapter to allow the use of ordinary
|
||||
// function as Users mutator.
|
||||
type UsersFunc func(context.Context, *ent.UsersMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f UsersFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
mv, ok := m.(*ent.UsersMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UsersMutation", m)
|
||||
}
|
||||
return f(ctx, mv)
|
||||
}
|
||||
|
||||
// Condition is a hook condition function.
|
||||
type Condition func(context.Context, ent.Mutation) bool
|
||||
|
||||
// And groups conditions with the AND operator.
|
||||
func And(first, second Condition, rest ...Condition) Condition {
|
||||
return func(ctx context.Context, m ent.Mutation) bool {
|
||||
if !first(ctx, m) || !second(ctx, m) {
|
||||
return false
|
||||
}
|
||||
for _, cond := range rest {
|
||||
if !cond(ctx, m) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Or groups conditions with the OR operator.
|
||||
func Or(first, second Condition, rest ...Condition) Condition {
|
||||
return func(ctx context.Context, m ent.Mutation) bool {
|
||||
if first(ctx, m) || second(ctx, m) {
|
||||
return true
|
||||
}
|
||||
for _, cond := range rest {
|
||||
if cond(ctx, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Not negates a given condition.
|
||||
func Not(cond Condition) Condition {
|
||||
return func(ctx context.Context, m ent.Mutation) bool {
|
||||
return !cond(ctx, m)
|
||||
}
|
||||
}
|
||||
|
||||
// HasOp is a condition testing mutation operation.
|
||||
func HasOp(op ent.Op) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
return m.Op().Is(op)
|
||||
}
|
||||
}
|
||||
|
||||
// HasAddedFields is a condition validating `.AddedField` on fields.
|
||||
func HasAddedFields(field string, fields ...string) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
if _, exists := m.AddedField(field); !exists {
|
||||
return false
|
||||
}
|
||||
for _, field := range fields {
|
||||
if _, exists := m.AddedField(field); !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// HasClearedFields is a condition validating `.FieldCleared` on fields.
|
||||
func HasClearedFields(field string, fields ...string) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
if exists := m.FieldCleared(field); !exists {
|
||||
return false
|
||||
}
|
||||
for _, field := range fields {
|
||||
if exists := m.FieldCleared(field); !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// HasFields is a condition validating `.Field` on fields.
|
||||
func HasFields(field string, fields ...string) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
if _, exists := m.Field(field); !exists {
|
||||
return false
|
||||
}
|
||||
for _, field := range fields {
|
||||
if _, exists := m.Field(field); !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// If executes the given hook under condition.
|
||||
//
|
||||
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
|
||||
//
|
||||
func If(hk ent.Hook, cond Condition) ent.Hook {
|
||||
return func(next ent.Mutator) ent.Mutator {
|
||||
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if cond(ctx, m) {
|
||||
return hk(next).Mutate(ctx, m)
|
||||
}
|
||||
return next.Mutate(ctx, m)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// On executes the given hook only for the given operation.
|
||||
//
|
||||
// hook.On(Log, ent.Delete|ent.Create)
|
||||
//
|
||||
func On(hk ent.Hook, op ent.Op) ent.Hook {
|
||||
return If(hk, HasOp(op))
|
||||
}
|
||||
|
||||
// Unless skips the given hook only for the given operation.
|
||||
//
|
||||
// hook.Unless(Log, ent.Update|ent.UpdateOne)
|
||||
//
|
||||
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
|
||||
return If(hk, Not(HasOp(op)))
|
||||
}
|
||||
|
||||
// FixedError is a hook returning a fixed error.
|
||||
func FixedError(err error) ent.Hook {
|
||||
return func(ent.Mutator) ent.Mutator {
|
||||
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
|
||||
return nil, err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Reject returns a hook that rejects all operations that match op.
|
||||
//
|
||||
// func (T) Hooks() []ent.Hook {
|
||||
// return []ent.Hook{
|
||||
// Reject(ent.Delete|ent.Update),
|
||||
// }
|
||||
// }
|
||||
//
|
||||
func Reject(op ent.Op) ent.Hook {
|
||||
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
|
||||
return On(hk, op)
|
||||
}
|
||||
|
||||
// Chain acts as a list of hooks and is effectively immutable.
|
||||
// Once created, it will always hold the same set of hooks in the same order.
|
||||
type Chain struct {
|
||||
hooks []ent.Hook
|
||||
}
|
||||
|
||||
// NewChain creates a new chain of hooks.
|
||||
func NewChain(hooks ...ent.Hook) Chain {
|
||||
return Chain{append([]ent.Hook(nil), hooks...)}
|
||||
}
|
||||
|
||||
// Hook chains the list of hooks and returns the final hook.
|
||||
func (c Chain) Hook() ent.Hook {
|
||||
return func(mutator ent.Mutator) ent.Mutator {
|
||||
for i := len(c.hooks) - 1; i >= 0; i-- {
|
||||
mutator = c.hooks[i](mutator)
|
||||
}
|
||||
return mutator
|
||||
}
|
||||
}
|
||||
|
||||
// Append extends a chain, adding the specified hook
|
||||
// as the last ones in the mutation flow.
|
||||
func (c Chain) Append(hooks ...ent.Hook) Chain {
|
||||
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
|
||||
newHooks = append(newHooks, c.hooks...)
|
||||
newHooks = append(newHooks, hooks...)
|
||||
return Chain{newHooks}
|
||||
}
|
||||
|
||||
// Extend extends a chain, adding the specified chain
|
||||
// as the last ones in the mutation flow.
|
||||
func (c Chain) Extend(chain Chain) Chain {
|
||||
return c.Append(chain.hooks...)
|
||||
}
|
224
ent/http/create.go
Normal file
224
ent/http/create.go
Normal file
@ -0,0 +1,224 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"t/ent"
|
||||
"t/ent/compartment"
|
||||
"t/ent/entry"
|
||||
"t/ent/fridge"
|
||||
"t/ent/item"
|
||||
|
||||
"github.com/mailru/easyjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Create creates a new ent.Compartment and stores it in the database.
|
||||
func (h CompartmentHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Create"))
|
||||
// Get the post data.
|
||||
var d CompartmentCreateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Compartment.Create()
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
default:
|
||||
l.Error("could not create compartment", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Store id of fresh entity to log errors for the reload.
|
||||
id := e.ID
|
||||
// Reload entry.
|
||||
q := h.client.Compartment.Query().Where(compartment.ID(e.ID))
|
||||
ret, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read compartment", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("compartment rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446View(ret), w)
|
||||
}
|
||||
|
||||
// Create creates a new ent.Entry and stores it in the database.
|
||||
func (h EntryHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Create"))
|
||||
// Get the post data.
|
||||
var d EntryCreateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Validate the data.
|
||||
errs := make(map[string]string)
|
||||
if d.User == nil {
|
||||
errs["user"] = `missing required field: "user"`
|
||||
} else if err := entry.UserValidator(*d.User); err != nil {
|
||||
errs["user"] = strings.TrimPrefix(err.Error(), "entry: ")
|
||||
}
|
||||
if d.First == nil {
|
||||
errs["first"] = `missing required field: "first"`
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
l.Info("validation failed", zapFields(errs)...)
|
||||
BadRequest(w, errs)
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Entry.Create()
|
||||
if d.User != nil {
|
||||
b.SetUser(*d.User)
|
||||
}
|
||||
if d.First != nil {
|
||||
b.SetFirst(*d.First)
|
||||
}
|
||||
if d.CreatedAt != nil {
|
||||
b.SetCreatedAt(*d.CreatedAt)
|
||||
}
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
default:
|
||||
l.Error("could not create entry", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Store id of fresh entity to log errors for the reload.
|
||||
id := e.ID
|
||||
// Reload entry.
|
||||
q := h.client.Entry.Query().Where(entry.ID(e.ID))
|
||||
ret, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.String("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.String("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read entry", zap.Error(err), zap.String("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("entry rendered", zap.String("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849View(ret), w)
|
||||
}
|
||||
|
||||
// Create creates a new ent.Fridge and stores it in the database.
|
||||
func (h FridgeHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Create"))
|
||||
// Get the post data.
|
||||
var d FridgeCreateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Fridge.Create()
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
default:
|
||||
l.Error("could not create fridge", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Store id of fresh entity to log errors for the reload.
|
||||
id := e.ID
|
||||
// Reload entry.
|
||||
q := h.client.Fridge.Query().Where(fridge.ID(e.ID))
|
||||
ret, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read fridge", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("fridge rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377View(ret), w)
|
||||
}
|
||||
|
||||
// Create creates a new ent.Item and stores it in the database.
|
||||
func (h ItemHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Create"))
|
||||
// Get the post data.
|
||||
var d ItemCreateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Item.Create()
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
default:
|
||||
l.Error("could not create item", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Store id of fresh entity to log errors for the reload.
|
||||
id := e.ID
|
||||
// Reload entry.
|
||||
q := h.client.Item.Query().Where(item.ID(e.ID))
|
||||
ret, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read item", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("item rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123View(ret), w)
|
||||
}
|
116
ent/http/delete.go
Normal file
116
ent/http/delete.go
Normal file
@ -0,0 +1,116 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"t/ent"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Delete removes a ent.Compartment from the database.
|
||||
func (h CompartmentHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Delete"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
err = h.client.Compartment.DeleteOneID(id).Exec(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
default:
|
||||
l.Error("could-not-delete-compartment", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("compartment deleted", zap.Int("id", id))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// Delete removes a ent.Entry from the database.
|
||||
func (h EntryHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Delete"))
|
||||
// ID is URL parameter.
|
||||
var err error
|
||||
id := chi.URLParam(r, "id")
|
||||
err = h.client.Entry.DeleteOneID(id).Exec(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.String("id", id))
|
||||
NotFound(w, msg)
|
||||
default:
|
||||
l.Error("could-not-delete-entry", zap.Error(err), zap.String("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("entry deleted", zap.String("id", id))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// Delete removes a ent.Fridge from the database.
|
||||
func (h FridgeHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Delete"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
err = h.client.Fridge.DeleteOneID(id).Exec(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
default:
|
||||
l.Error("could-not-delete-fridge", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("fridge deleted", zap.Int("id", id))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// Delete removes a ent.Item from the database.
|
||||
func (h ItemHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Delete"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
err = h.client.Item.DeleteOneID(id).Exec(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
default:
|
||||
l.Error("could-not-delete-item", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("item deleted", zap.Int("id", id))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
1075
ent/http/easyjson.go
Normal file
1075
ent/http/easyjson.go
Normal file
File diff suppressed because it is too large
Load Diff
185
ent/http/handler.go
Normal file
185
ent/http/handler.go
Normal file
@ -0,0 +1,185 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"t/ent"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// NewHandler returns a ready to use handler with all generated endpoints mounted.
|
||||
func NewHandler(c *ent.Client, l *zap.Logger) chi.Router {
|
||||
r := chi.NewRouter()
|
||||
MountRoutes(c, l, r)
|
||||
return r
|
||||
}
|
||||
|
||||
// MountRoutes mounts all generated routes on the given router.
|
||||
func MountRoutes(c *ent.Client, l *zap.Logger, r chi.Router) {
|
||||
NewCompartmentHandler(c, l).MountRoutes(r)
|
||||
NewEntryHandler(c, l).MountRoutes(r)
|
||||
NewFridgeHandler(c, l).MountRoutes(r)
|
||||
NewItemHandler(c, l).MountRoutes(r)
|
||||
}
|
||||
|
||||
// CompartmentHandler handles http crud operations on ent.Compartment.
|
||||
type CompartmentHandler struct {
|
||||
client *ent.Client
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
func NewCompartmentHandler(c *ent.Client, l *zap.Logger) *CompartmentHandler {
|
||||
return &CompartmentHandler{
|
||||
client: c,
|
||||
log: l.With(zap.String("handler", "CompartmentHandler")),
|
||||
}
|
||||
}
|
||||
func (h *CompartmentHandler) MountCreateRoute(r chi.Router) *CompartmentHandler {
|
||||
r.Post("/compartments", h.Create)
|
||||
return h
|
||||
}
|
||||
func (h *CompartmentHandler) MountReadRoute(r chi.Router) *CompartmentHandler {
|
||||
r.Get("/compartments/{id}", h.Read)
|
||||
return h
|
||||
}
|
||||
func (h *CompartmentHandler) MountUpdateRoute(r chi.Router) *CompartmentHandler {
|
||||
r.Patch("/compartments/{id}", h.Update)
|
||||
return h
|
||||
}
|
||||
func (h *CompartmentHandler) MountDeleteRoute(r chi.Router) *CompartmentHandler {
|
||||
r.Delete("/compartments/{id}", h.Delete)
|
||||
return h
|
||||
}
|
||||
func (h *CompartmentHandler) MountListRoute(r chi.Router) *CompartmentHandler {
|
||||
r.Get("/compartments", h.List)
|
||||
return h
|
||||
}
|
||||
func (h *CompartmentHandler) MountRoutes(r chi.Router) {
|
||||
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
|
||||
}
|
||||
|
||||
// EntryHandler handles http crud operations on ent.Entry.
|
||||
type EntryHandler struct {
|
||||
client *ent.Client
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
func NewEntryHandler(c *ent.Client, l *zap.Logger) *EntryHandler {
|
||||
return &EntryHandler{
|
||||
client: c,
|
||||
log: l.With(zap.String("handler", "EntryHandler")),
|
||||
}
|
||||
}
|
||||
func (h *EntryHandler) MountCreateRoute(r chi.Router) *EntryHandler {
|
||||
r.Post("/entries", h.Create)
|
||||
return h
|
||||
}
|
||||
func (h *EntryHandler) MountReadRoute(r chi.Router) *EntryHandler {
|
||||
r.Get("/entries/{id}", h.Read)
|
||||
return h
|
||||
}
|
||||
func (h *EntryHandler) MountUpdateRoute(r chi.Router) *EntryHandler {
|
||||
r.Patch("/entries/{id}", h.Update)
|
||||
return h
|
||||
}
|
||||
func (h *EntryHandler) MountDeleteRoute(r chi.Router) *EntryHandler {
|
||||
r.Delete("/entries/{id}", h.Delete)
|
||||
return h
|
||||
}
|
||||
func (h *EntryHandler) MountListRoute(r chi.Router) *EntryHandler {
|
||||
r.Get("/entries", h.List)
|
||||
return h
|
||||
}
|
||||
func (h *EntryHandler) MountRoutes(r chi.Router) {
|
||||
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
|
||||
}
|
||||
|
||||
// FridgeHandler handles http crud operations on ent.Fridge.
|
||||
type FridgeHandler struct {
|
||||
client *ent.Client
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
func NewFridgeHandler(c *ent.Client, l *zap.Logger) *FridgeHandler {
|
||||
return &FridgeHandler{
|
||||
client: c,
|
||||
log: l.With(zap.String("handler", "FridgeHandler")),
|
||||
}
|
||||
}
|
||||
func (h *FridgeHandler) MountCreateRoute(r chi.Router) *FridgeHandler {
|
||||
r.Post("/fridges", h.Create)
|
||||
return h
|
||||
}
|
||||
func (h *FridgeHandler) MountReadRoute(r chi.Router) *FridgeHandler {
|
||||
r.Get("/fridges/{id}", h.Read)
|
||||
return h
|
||||
}
|
||||
func (h *FridgeHandler) MountUpdateRoute(r chi.Router) *FridgeHandler {
|
||||
r.Patch("/fridges/{id}", h.Update)
|
||||
return h
|
||||
}
|
||||
func (h *FridgeHandler) MountDeleteRoute(r chi.Router) *FridgeHandler {
|
||||
r.Delete("/fridges/{id}", h.Delete)
|
||||
return h
|
||||
}
|
||||
func (h *FridgeHandler) MountListRoute(r chi.Router) *FridgeHandler {
|
||||
r.Get("/fridges", h.List)
|
||||
return h
|
||||
}
|
||||
func (h *FridgeHandler) MountRoutes(r chi.Router) {
|
||||
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
|
||||
}
|
||||
|
||||
// ItemHandler handles http crud operations on ent.Item.
|
||||
type ItemHandler struct {
|
||||
client *ent.Client
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
func NewItemHandler(c *ent.Client, l *zap.Logger) *ItemHandler {
|
||||
return &ItemHandler{
|
||||
client: c,
|
||||
log: l.With(zap.String("handler", "ItemHandler")),
|
||||
}
|
||||
}
|
||||
func (h *ItemHandler) MountCreateRoute(r chi.Router) *ItemHandler {
|
||||
r.Post("/items", h.Create)
|
||||
return h
|
||||
}
|
||||
func (h *ItemHandler) MountReadRoute(r chi.Router) *ItemHandler {
|
||||
r.Get("/items/{id}", h.Read)
|
||||
return h
|
||||
}
|
||||
func (h *ItemHandler) MountUpdateRoute(r chi.Router) *ItemHandler {
|
||||
r.Patch("/items/{id}", h.Update)
|
||||
return h
|
||||
}
|
||||
func (h *ItemHandler) MountDeleteRoute(r chi.Router) *ItemHandler {
|
||||
r.Delete("/items/{id}", h.Delete)
|
||||
return h
|
||||
}
|
||||
func (h *ItemHandler) MountListRoute(r chi.Router) *ItemHandler {
|
||||
r.Get("/items", h.List)
|
||||
return h
|
||||
}
|
||||
func (h *ItemHandler) MountRoutes(r chi.Router) {
|
||||
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
|
||||
}
|
||||
|
||||
func stripEntError(err error) string {
|
||||
return strings.TrimPrefix(err.Error(), "ent: ")
|
||||
}
|
||||
|
||||
func zapFields(errs map[string]string) []zap.Field {
|
||||
if errs == nil || len(errs) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make([]zap.Field, 0)
|
||||
for k, v := range errs {
|
||||
r = append(r, zap.String(k, v))
|
||||
}
|
||||
return r
|
||||
}
|
147
ent/http/list.go
Normal file
147
ent/http/list.go
Normal file
@ -0,0 +1,147 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/mailru/easyjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Read fetches the ent.Compartment identified by a given url-parameter from the
|
||||
// database and returns it to the client.
|
||||
func (h *CompartmentHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "List"))
|
||||
q := h.client.Compartment.Query()
|
||||
var err error
|
||||
page := 1
|
||||
if d := r.URL.Query().Get("page"); d != "" {
|
||||
page, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
|
||||
BadRequest(w, "page must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
itemsPerPage := 30
|
||||
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
|
||||
itemsPerPage, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
|
||||
BadRequest(w, "itemsPerPage must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
|
||||
if err != nil {
|
||||
l.Error("error fetching compartments from db", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
return
|
||||
}
|
||||
l.Info("compartments rendered", zap.Int("amount", len(es)))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446Views(es), w)
|
||||
}
|
||||
|
||||
// Read fetches the ent.Entry identified by a given url-parameter from the
|
||||
// database and returns it to the client.
|
||||
func (h *EntryHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "List"))
|
||||
q := h.client.Entry.Query()
|
||||
var err error
|
||||
page := 1
|
||||
if d := r.URL.Query().Get("page"); d != "" {
|
||||
page, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
|
||||
BadRequest(w, "page must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
itemsPerPage := 30
|
||||
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
|
||||
itemsPerPage, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
|
||||
BadRequest(w, "itemsPerPage must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
|
||||
if err != nil {
|
||||
l.Error("error fetching entries from db", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
return
|
||||
}
|
||||
l.Info("entries rendered", zap.Int("amount", len(es)))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849Views(es), w)
|
||||
}
|
||||
|
||||
// Read fetches the ent.Fridge identified by a given url-parameter from the
|
||||
// database and returns it to the client.
|
||||
func (h *FridgeHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "List"))
|
||||
q := h.client.Fridge.Query()
|
||||
var err error
|
||||
page := 1
|
||||
if d := r.URL.Query().Get("page"); d != "" {
|
||||
page, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
|
||||
BadRequest(w, "page must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
itemsPerPage := 30
|
||||
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
|
||||
itemsPerPage, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
|
||||
BadRequest(w, "itemsPerPage must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
|
||||
if err != nil {
|
||||
l.Error("error fetching fridges from db", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
return
|
||||
}
|
||||
l.Info("fridges rendered", zap.Int("amount", len(es)))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377Views(es), w)
|
||||
}
|
||||
|
||||
// Read fetches the ent.Item identified by a given url-parameter from the
|
||||
// database and returns it to the client.
|
||||
func (h *ItemHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "List"))
|
||||
q := h.client.Item.Query()
|
||||
var err error
|
||||
page := 1
|
||||
if d := r.URL.Query().Get("page"); d != "" {
|
||||
page, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
|
||||
BadRequest(w, "page must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
itemsPerPage := 30
|
||||
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
|
||||
itemsPerPage, err = strconv.Atoi(d)
|
||||
if err != nil {
|
||||
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
|
||||
BadRequest(w, "itemsPerPage must be an integer greater zero")
|
||||
return
|
||||
}
|
||||
}
|
||||
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
|
||||
if err != nil {
|
||||
l.Error("error fetching items from db", zap.Error(err))
|
||||
InternalServerError(w, nil)
|
||||
return
|
||||
}
|
||||
l.Info("items rendered", zap.Int("amount", len(es)))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123Views(es), w)
|
||||
}
|
149
ent/http/read.go
Normal file
149
ent/http/read.go
Normal file
@ -0,0 +1,149 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"t/ent"
|
||||
"t/ent/compartment"
|
||||
"t/ent/entry"
|
||||
"t/ent/fridge"
|
||||
"t/ent/item"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/mailru/easyjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Read fetches the ent.Compartment identified by a given url-parameter from the
|
||||
// database and renders it to the client.
|
||||
func (h *CompartmentHandler) Read(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Read"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
// Create the query to fetch the Compartment
|
||||
q := h.client.Compartment.Query().Where(compartment.ID(id))
|
||||
e, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read compartment", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("compartment rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446View(e), w)
|
||||
}
|
||||
|
||||
// Read fetches the ent.Entry identified by a given url-parameter from the
|
||||
// database and renders it to the client.
|
||||
func (h *EntryHandler) Read(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Read"))
|
||||
// ID is URL parameter.
|
||||
var err error
|
||||
id := chi.URLParam(r, "id")
|
||||
// Create the query to fetch the Entry
|
||||
q := h.client.Entry.Query().Where(entry.ID(id))
|
||||
e, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.String("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.String("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read entry", zap.Error(err), zap.String("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("entry rendered", zap.String("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849View(e), w)
|
||||
}
|
||||
|
||||
// Read fetches the ent.Fridge identified by a given url-parameter from the
|
||||
// database and renders it to the client.
|
||||
func (h *FridgeHandler) Read(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Read"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
// Create the query to fetch the Fridge
|
||||
q := h.client.Fridge.Query().Where(fridge.ID(id))
|
||||
e, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read fridge", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("fridge rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377View(e), w)
|
||||
}
|
||||
|
||||
// Read fetches the ent.Item identified by a given url-parameter from the
|
||||
// database and renders it to the client.
|
||||
func (h *ItemHandler) Read(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Read"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
// Create the query to fetch the Item
|
||||
q := h.client.Item.Query().Where(item.ID(id))
|
||||
e, err := q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could not read item", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("item rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123View(e), w)
|
||||
}
|
3
ent/http/relations.go
Normal file
3
ent/http/relations.go
Normal file
@ -0,0 +1,3 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
42
ent/http/request.go
Normal file
42
ent/http/request.go
Normal file
@ -0,0 +1,42 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Payload of a ent.Compartment create request.
|
||||
type CompartmentCreateRequest struct {
|
||||
}
|
||||
|
||||
// Payload of a ent.Compartment update request.
|
||||
type CompartmentUpdateRequest struct {
|
||||
}
|
||||
|
||||
// Payload of a ent.Entry create request.
|
||||
type EntryCreateRequest struct {
|
||||
User *string `json:"user"`
|
||||
First *int `json:"first"`
|
||||
CreatedAt *time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Payload of a ent.Entry update request.
|
||||
type EntryUpdateRequest struct {
|
||||
}
|
||||
|
||||
// Payload of a ent.Fridge create request.
|
||||
type FridgeCreateRequest struct {
|
||||
}
|
||||
|
||||
// Payload of a ent.Fridge update request.
|
||||
type FridgeUpdateRequest struct {
|
||||
}
|
||||
|
||||
// Payload of a ent.Item create request.
|
||||
type ItemCreateRequest struct {
|
||||
}
|
||||
|
||||
// Payload of a ent.Item update request.
|
||||
type ItemUpdateRequest struct {
|
||||
}
|
200
ent/http/response.go
Normal file
200
ent/http/response.go
Normal file
@ -0,0 +1,200 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"t/ent"
|
||||
"time"
|
||||
|
||||
"github.com/mailru/easyjson"
|
||||
)
|
||||
|
||||
// Basic HTTP Error Response
|
||||
type ErrResponse struct {
|
||||
Code int `json:"code"` // http response status code
|
||||
Status string `json:"status"` // user-level status message
|
||||
Errors interface{} `json:"errors,omitempty"` // application-level error
|
||||
}
|
||||
|
||||
func (e ErrResponse) MarshalToHTTPResponseWriter(w http.ResponseWriter) (int, error) {
|
||||
d, err := easyjson.Marshal(e)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(d)))
|
||||
w.WriteHeader(e.Code)
|
||||
return w.Write(d)
|
||||
}
|
||||
|
||||
func BadRequest(w http.ResponseWriter, msg interface{}) (int, error) {
|
||||
return ErrResponse{
|
||||
Code: http.StatusBadRequest,
|
||||
Status: http.StatusText(http.StatusBadRequest),
|
||||
Errors: msg,
|
||||
}.MarshalToHTTPResponseWriter(w)
|
||||
}
|
||||
|
||||
func Conflict(w http.ResponseWriter, msg interface{}) (int, error) {
|
||||
return ErrResponse{
|
||||
Code: http.StatusConflict,
|
||||
Status: http.StatusText(http.StatusConflict),
|
||||
Errors: msg,
|
||||
}.MarshalToHTTPResponseWriter(w)
|
||||
}
|
||||
|
||||
func Forbidden(w http.ResponseWriter, msg interface{}) (int, error) {
|
||||
return ErrResponse{
|
||||
Code: http.StatusForbidden,
|
||||
Status: http.StatusText(http.StatusForbidden),
|
||||
Errors: msg,
|
||||
}.MarshalToHTTPResponseWriter(w)
|
||||
}
|
||||
|
||||
func InternalServerError(w http.ResponseWriter, msg interface{}) (int, error) {
|
||||
return ErrResponse{
|
||||
Code: http.StatusInternalServerError,
|
||||
Status: http.StatusText(http.StatusInternalServerError),
|
||||
Errors: msg,
|
||||
}.MarshalToHTTPResponseWriter(w)
|
||||
}
|
||||
|
||||
func NotFound(w http.ResponseWriter, msg interface{}) (int, error) {
|
||||
return ErrResponse{
|
||||
Code: http.StatusNotFound,
|
||||
Status: http.StatusText(http.StatusNotFound),
|
||||
Errors: msg,
|
||||
}.MarshalToHTTPResponseWriter(w)
|
||||
}
|
||||
|
||||
func Unauthorized(w http.ResponseWriter, msg interface{}) (int, error) {
|
||||
return ErrResponse{
|
||||
Code: http.StatusUnauthorized,
|
||||
Status: http.StatusText(http.StatusUnauthorized),
|
||||
Errors: msg,
|
||||
}.MarshalToHTTPResponseWriter(w)
|
||||
}
|
||||
|
||||
type (
|
||||
// Compartment3324871446View represents the data serialized for the following serialization group combinations:
|
||||
// []
|
||||
Compartment3324871446View struct {
|
||||
ID int `json:"id,omitempty"`
|
||||
}
|
||||
Compartment3324871446Views []*Compartment3324871446View
|
||||
)
|
||||
|
||||
func NewCompartment3324871446View(e *ent.Compartment) *Compartment3324871446View {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &Compartment3324871446View{
|
||||
ID: e.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func NewCompartment3324871446Views(es []*ent.Compartment) Compartment3324871446Views {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make(Compartment3324871446Views, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewCompartment3324871446View(e)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
type (
|
||||
// Entry2675665849View represents the data serialized for the following serialization group combinations:
|
||||
// []
|
||||
Entry2675665849View struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
User string `json:"user,omitempty"`
|
||||
First int `json:"first,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
}
|
||||
Entry2675665849Views []*Entry2675665849View
|
||||
)
|
||||
|
||||
func NewEntry2675665849View(e *ent.Entry) *Entry2675665849View {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &Entry2675665849View{
|
||||
ID: e.ID,
|
||||
User: e.User,
|
||||
First: e.First,
|
||||
CreatedAt: e.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func NewEntry2675665849Views(es []*ent.Entry) Entry2675665849Views {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make(Entry2675665849Views, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewEntry2675665849View(e)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
type (
|
||||
// Fridge2211356377View represents the data serialized for the following serialization group combinations:
|
||||
// []
|
||||
Fridge2211356377View struct {
|
||||
ID int `json:"id,omitempty"`
|
||||
}
|
||||
Fridge2211356377Views []*Fridge2211356377View
|
||||
)
|
||||
|
||||
func NewFridge2211356377View(e *ent.Fridge) *Fridge2211356377View {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &Fridge2211356377View{
|
||||
ID: e.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func NewFridge2211356377Views(es []*ent.Fridge) Fridge2211356377Views {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make(Fridge2211356377Views, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewFridge2211356377View(e)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
type (
|
||||
// Item1548468123View represents the data serialized for the following serialization group combinations:
|
||||
// []
|
||||
Item1548468123View struct {
|
||||
ID int `json:"id,omitempty"`
|
||||
}
|
||||
Item1548468123Views []*Item1548468123View
|
||||
)
|
||||
|
||||
func NewItem1548468123View(e *ent.Item) *Item1548468123View {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &Item1548468123View{
|
||||
ID: e.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func NewItem1548468123Views(es []*ent.Item) Item1548468123Views {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make(Item1548468123Views, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewItem1548468123View(e)
|
||||
}
|
||||
return r
|
||||
}
|
260
ent/http/update.go
Normal file
260
ent/http/update.go
Normal file
@ -0,0 +1,260 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"t/ent"
|
||||
"t/ent/compartment"
|
||||
"t/ent/entry"
|
||||
"t/ent/fridge"
|
||||
"t/ent/item"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/mailru/easyjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Update updates a given ent.Compartment and saves the changes to the database.
|
||||
func (h CompartmentHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Update"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
// Get the post data.
|
||||
var d CompartmentUpdateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Compartment.UpdateOneID(id)
|
||||
// Store in database.
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-update-compartment", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Reload entry.
|
||||
q := h.client.Compartment.Query().Where(compartment.ID(e.ID))
|
||||
e, err = q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-read-compartment", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("compartment rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446View(e), w)
|
||||
}
|
||||
|
||||
// Update updates a given ent.Entry and saves the changes to the database.
|
||||
func (h EntryHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Update"))
|
||||
// ID is URL parameter.
|
||||
var err error
|
||||
id := chi.URLParam(r, "id")
|
||||
// Get the post data.
|
||||
var d EntryUpdateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Validate the data.
|
||||
errs := make(map[string]string)
|
||||
if len(errs) > 0 {
|
||||
l.Info("validation failed", zapFields(errs)...)
|
||||
BadRequest(w, errs)
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Entry.UpdateOneID(id)
|
||||
// Store in database.
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.String("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.String("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-update-entry", zap.Error(err), zap.String("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Reload entry.
|
||||
q := h.client.Entry.Query().Where(entry.ID(e.ID))
|
||||
e, err = q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.String("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.String("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-read-entry", zap.Error(err), zap.String("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("entry rendered", zap.String("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849View(e), w)
|
||||
}
|
||||
|
||||
// Update updates a given ent.Fridge and saves the changes to the database.
|
||||
func (h FridgeHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Update"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
// Get the post data.
|
||||
var d FridgeUpdateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Fridge.UpdateOneID(id)
|
||||
// Store in database.
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-update-fridge", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Reload entry.
|
||||
q := h.client.Fridge.Query().Where(fridge.ID(e.ID))
|
||||
e, err = q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-read-fridge", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("fridge rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377View(e), w)
|
||||
}
|
||||
|
||||
// Update updates a given ent.Item and saves the changes to the database.
|
||||
func (h ItemHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
l := h.log.With(zap.String("method", "Update"))
|
||||
// ID is URL parameter.
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
|
||||
BadRequest(w, "id must be an integer")
|
||||
return
|
||||
}
|
||||
// Get the post data.
|
||||
var d ItemUpdateRequest
|
||||
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
|
||||
l.Error("error decoding json", zap.Error(err))
|
||||
BadRequest(w, "invalid json string")
|
||||
return
|
||||
}
|
||||
// Save the data.
|
||||
b := h.client.Item.UpdateOneID(id)
|
||||
// Store in database.
|
||||
e, err := b.Save(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-update-item", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Reload entry.
|
||||
q := h.client.Item.Query().Where(item.ID(e.ID))
|
||||
e, err = q.Only(r.Context())
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
msg := stripEntError(err)
|
||||
l.Info(msg, zap.Error(err), zap.Int("id", id))
|
||||
NotFound(w, msg)
|
||||
case ent.IsNotSingular(err):
|
||||
msg := stripEntError(err)
|
||||
l.Error(msg, zap.Error(err), zap.Int("id", id))
|
||||
BadRequest(w, msg)
|
||||
default:
|
||||
l.Error("could-not-read-item", zap.Error(err), zap.Int("id", id))
|
||||
InternalServerError(w, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
l.Info("item rendered", zap.Int("id", id))
|
||||
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123View(e), w)
|
||||
}
|
71
ent/migrate/migrate.go
Normal file
71
ent/migrate/migrate.go
Normal file
@ -0,0 +1,71 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
// WithGlobalUniqueID sets the universal ids options to the migration.
|
||||
// If this option is enabled, ent migration will allocate a 1<<32 range
|
||||
// for the ids of each entity (table).
|
||||
// Note that this option cannot be applied on tables that already exist.
|
||||
WithGlobalUniqueID = schema.WithGlobalUniqueID
|
||||
// WithDropColumn sets the drop column option to the migration.
|
||||
// If this option is enabled, ent migration will drop old columns
|
||||
// that were used for both fields and edges. This defaults to false.
|
||||
WithDropColumn = schema.WithDropColumn
|
||||
// WithDropIndex sets the drop index option to the migration.
|
||||
// If this option is enabled, ent migration will drop old indexes
|
||||
// that were defined in the schema. This defaults to false.
|
||||
// Note that unique constraints are defined using `UNIQUE INDEX`,
|
||||
// and therefore, it's recommended to enable this option to get more
|
||||
// flexibility in the schema changes.
|
||||
WithDropIndex = schema.WithDropIndex
|
||||
// WithFixture sets the foreign-key renaming option to the migration when upgrading
|
||||
// ent from v0.1.0 (issue-#285). Defaults to false.
|
||||
WithFixture = schema.WithFixture
|
||||
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
|
||||
WithForeignKeys = schema.WithForeignKeys
|
||||
)
|
||||
|
||||
// Schema is the API for creating, migrating and dropping a schema.
|
||||
type Schema struct {
|
||||
drv dialect.Driver
|
||||
}
|
||||
|
||||
// NewSchema creates a new schema client.
|
||||
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
|
||||
|
||||
// Create creates all schema resources.
|
||||
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
|
||||
migrate, err := schema.NewMigrate(s.drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.Create(ctx, Tables...)
|
||||
}
|
||||
|
||||
// WriteTo writes the schema changes to w instead of running them against the database.
|
||||
//
|
||||
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
//
|
||||
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
|
||||
drv := &schema.WriteDriver{
|
||||
Writer: w,
|
||||
Driver: s.drv,
|
||||
}
|
||||
migrate, err := schema.NewMigrate(drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.Create(ctx, Tables...)
|
||||
}
|
46
ent/migrate/schema.go
Normal file
46
ent/migrate/schema.go
Normal file
@ -0,0 +1,46 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
var (
|
||||
// UsersColumns holds the columns for the "users" table.
|
||||
UsersColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "user", Type: field.TypeString, Unique: true, Size: 7},
|
||||
{Name: "chara", Type: field.TypeString, Nullable: true, Default: "ponta"},
|
||||
{Name: "skill", Type: field.TypeInt, Nullable: true, Default: 7},
|
||||
{Name: "hp", Type: field.TypeInt, Nullable: true, Default: 7},
|
||||
{Name: "attack", Type: field.TypeInt, Nullable: true, Default: 8},
|
||||
{Name: "defense", Type: field.TypeInt, Nullable: true, Default: 19},
|
||||
{Name: "critical", Type: field.TypeInt, Nullable: true, Default: 7},
|
||||
{Name: "battle", Type: field.TypeInt, Nullable: true, Default: 1},
|
||||
{Name: "win", Type: field.TypeInt, Nullable: true, Default: 0},
|
||||
{Name: "day", Type: field.TypeInt, Nullable: true, Default: 0},
|
||||
{Name: "percentage", Type: field.TypeFloat64, Nullable: true, Default: 0},
|
||||
{Name: "limit", Type: field.TypeBool, Nullable: true, Default: false},
|
||||
{Name: "status", Type: field.TypeString, Nullable: true, Default: "normal"},
|
||||
{Name: "comment", Type: field.TypeString, Nullable: true, Default: ""},
|
||||
{Name: "created_at", Type: field.TypeTime, Nullable: true},
|
||||
{Name: "next", Type: field.TypeString, Nullable: true, Default: "20220617"},
|
||||
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
|
||||
{Name: "url", Type: field.TypeString, Nullable: true, Default: "https://syui.cf/api"},
|
||||
}
|
||||
// UsersTable holds the schema information for the "users" table.
|
||||
UsersTable = &schema.Table{
|
||||
Name: "users",
|
||||
Columns: UsersColumns,
|
||||
PrimaryKey: []*schema.Column{UsersColumns[0]},
|
||||
}
|
||||
// Tables holds all the tables in the schema.
|
||||
Tables = []*schema.Table{
|
||||
UsersTable,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
}
|
1891
ent/mutation.go
Normal file
1891
ent/mutation.go
Normal file
File diff suppressed because it is too large
Load Diff
165
ent/ogent/oas_cfg_gen.go
Normal file
165
ent/ogent/oas_cfg_gen.go
Normal file
@ -0,0 +1,165 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
// bufPool is pool of bytes.Buffer for encoding and decoding.
|
||||
var bufPool = &sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(bytes.Buffer)
|
||||
},
|
||||
}
|
||||
|
||||
// getBuf returns buffer from pool.
|
||||
func getBuf() *bytes.Buffer {
|
||||
return bufPool.Get().(*bytes.Buffer)
|
||||
}
|
||||
|
||||
// putBuf puts buffer to pool.
|
||||
func putBuf(b *bytes.Buffer) {
|
||||
b.Reset()
|
||||
bufPool.Put(b)
|
||||
}
|
||||
|
||||
type config struct {
|
||||
TracerProvider trace.TracerProvider
|
||||
Tracer trace.Tracer
|
||||
MeterProvider metric.MeterProvider
|
||||
Meter metric.Meter
|
||||
Client ht.Client
|
||||
NotFound http.HandlerFunc
|
||||
}
|
||||
|
||||
func newConfig(opts ...Option) config {
|
||||
cfg := config{
|
||||
TracerProvider: otel.GetTracerProvider(),
|
||||
MeterProvider: metric.NewNoopMeterProvider(),
|
||||
Client: http.DefaultClient,
|
||||
NotFound: http.NotFound,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.apply(&cfg)
|
||||
}
|
||||
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
|
||||
trace.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||
)
|
||||
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name)
|
||||
return cfg
|
||||
}
|
||||
|
||||
type Option interface {
|
||||
apply(*config)
|
||||
}
|
||||
|
||||
type optionFunc func(*config)
|
||||
|
||||
func (o optionFunc) apply(c *config) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
|
||||
//
|
||||
// If none is specified, the global provider is used.
|
||||
func WithTracerProvider(provider trace.TracerProvider) Option {
|
||||
return optionFunc(func(cfg *config) {
|
||||
if provider != nil {
|
||||
cfg.TracerProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMeterProvider specifies a meter provider to use for creating a meter.
|
||||
//
|
||||
// If none is specified, the metric.NewNoopMeterProvider is used.
|
||||
func WithMeterProvider(provider metric.MeterProvider) Option {
|
||||
return optionFunc(func(cfg *config) {
|
||||
if provider != nil {
|
||||
cfg.MeterProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithClient specifies http client to use.
|
||||
func WithClient(client ht.Client) Option {
|
||||
return optionFunc(func(cfg *config) {
|
||||
if client != nil {
|
||||
cfg.Client = client
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithNotFound specifies http handler to use.
|
||||
func WithNotFound(notFound http.HandlerFunc) Option {
|
||||
return optionFunc(func(cfg *config) {
|
||||
if notFound != nil {
|
||||
cfg.NotFound = notFound
|
||||
}
|
||||
})
|
||||
}
|
564
ent/ogent/oas_client_gen.go
Normal file
564
ent/ogent/oas_client_gen.go
Normal file
@ -0,0 +1,564 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
// Client implements OAS client.
|
||||
type Client struct {
|
||||
serverURL *url.URL
|
||||
cfg config
|
||||
requests metric.Int64Counter
|
||||
errors metric.Int64Counter
|
||||
duration metric.Int64Histogram
|
||||
}
|
||||
|
||||
// NewClient initializes new Client defined by OAS.
|
||||
func NewClient(serverURL string, opts ...Option) (*Client, error) {
|
||||
u, err := url.Parse(serverURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &Client{
|
||||
cfg: newConfig(opts...),
|
||||
serverURL: u,
|
||||
}
|
||||
if c.requests, err = c.cfg.Meter.NewInt64Counter(otelogen.ClientRequestCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.errors, err = c.cfg.Meter.NewInt64Counter(otelogen.ClientErrorsCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.duration, err = c.cfg.Meter.NewInt64Histogram(otelogen.ClientDuration); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// CreateUsers invokes createUsers operation.
|
||||
//
|
||||
// Creates a new Users and persists it to storage.
|
||||
//
|
||||
// POST /users
|
||||
func (c *Client) CreateUsers(ctx context.Context, request CreateUsersReq) (res CreateUsersRes, err error) {
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("createUsers"),
|
||||
}
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, "CreateUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
c.errors.Add(ctx, 1, otelAttrs...)
|
||||
} else {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
c.requests.Add(ctx, 1, otelAttrs...)
|
||||
var (
|
||||
contentType string
|
||||
reqBody io.Reader
|
||||
)
|
||||
contentType = "application/json"
|
||||
buf, err := encodeCreateUsersRequestJSON(request, span)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer jx.PutEncoder(buf)
|
||||
reqBody = bytes.NewReader(buf.Bytes())
|
||||
|
||||
u := uri.Clone(c.serverURL)
|
||||
u.Path += "/users"
|
||||
|
||||
r := ht.NewRequest(ctx, "POST", u, reqBody)
|
||||
defer ht.PutRequest(r)
|
||||
|
||||
r.Header.Set("Content-Type", contentType)
|
||||
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
result, err := decodeCreateUsersResponse(resp, span)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DeleteUsers invokes deleteUsers operation.
|
||||
//
|
||||
// Deletes the Users with the requested ID.
|
||||
//
|
||||
// DELETE /users/{id}
|
||||
func (c *Client) DeleteUsers(ctx context.Context, params DeleteUsersParams) (res DeleteUsersRes, err error) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("deleteUsers"),
|
||||
}
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, "DeleteUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
c.errors.Add(ctx, 1, otelAttrs...)
|
||||
} else {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
c.requests.Add(ctx, 1, otelAttrs...)
|
||||
u := uri.Clone(c.serverURL)
|
||||
u.Path += "/users/"
|
||||
{
|
||||
// Encode "id" parameter.
|
||||
e := uri.NewPathEncoder(uri.PathEncoderConfig{
|
||||
Param: "id",
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
if err := func() error {
|
||||
return e.EncodeValue(conv.IntToString(params.ID))
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "encode path")
|
||||
}
|
||||
u.Path += e.Result()
|
||||
}
|
||||
|
||||
r := ht.NewRequest(ctx, "DELETE", u, nil)
|
||||
defer ht.PutRequest(r)
|
||||
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
result, err := decodeDeleteUsersResponse(resp, span)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DrawDone invokes drawDone operation.
|
||||
//
|
||||
// PUT /users/{id}/d
|
||||
func (c *Client) DrawDone(ctx context.Context, params DrawDoneParams) (res DrawDoneNoContent, err error) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("drawDone"),
|
||||
}
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, "DrawDone",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
c.errors.Add(ctx, 1, otelAttrs...)
|
||||
} else {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
c.requests.Add(ctx, 1, otelAttrs...)
|
||||
u := uri.Clone(c.serverURL)
|
||||
u.Path += "/users/"
|
||||
{
|
||||
// Encode "id" parameter.
|
||||
e := uri.NewPathEncoder(uri.PathEncoderConfig{
|
||||
Param: "id",
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
if err := func() error {
|
||||
return e.EncodeValue(conv.IntToString(params.ID))
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "encode path")
|
||||
}
|
||||
u.Path += e.Result()
|
||||
}
|
||||
u.Path += "/d"
|
||||
|
||||
r := ht.NewRequest(ctx, "PUT", u, nil)
|
||||
defer ht.PutRequest(r)
|
||||
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
result, err := decodeDrawDoneResponse(resp, span)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DrawStart invokes drawStart operation.
|
||||
//
|
||||
// PATCH /users/{id}/start
|
||||
func (c *Client) DrawStart(ctx context.Context, params DrawStartParams) (res DrawStartNoContent, err error) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("drawStart"),
|
||||
}
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, "DrawStart",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
c.errors.Add(ctx, 1, otelAttrs...)
|
||||
} else {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
c.requests.Add(ctx, 1, otelAttrs...)
|
||||
u := uri.Clone(c.serverURL)
|
||||
u.Path += "/users/"
|
||||
{
|
||||
// Encode "id" parameter.
|
||||
e := uri.NewPathEncoder(uri.PathEncoderConfig{
|
||||
Param: "id",
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
if err := func() error {
|
||||
return e.EncodeValue(conv.IntToString(params.ID))
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "encode path")
|
||||
}
|
||||
u.Path += e.Result()
|
||||
}
|
||||
u.Path += "/start"
|
||||
|
||||
r := ht.NewRequest(ctx, "PATCH", u, nil)
|
||||
defer ht.PutRequest(r)
|
||||
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
result, err := decodeDrawStartResponse(resp, span)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListUsers invokes listUsers operation.
|
||||
//
|
||||
// List Users.
|
||||
//
|
||||
// GET /users
|
||||
func (c *Client) ListUsers(ctx context.Context, params ListUsersParams) (res ListUsersRes, err error) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("listUsers"),
|
||||
}
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, "ListUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
c.errors.Add(ctx, 1, otelAttrs...)
|
||||
} else {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
c.requests.Add(ctx, 1, otelAttrs...)
|
||||
u := uri.Clone(c.serverURL)
|
||||
u.Path += "/users"
|
||||
|
||||
q := u.Query()
|
||||
{
|
||||
// Encode "page" parameter.
|
||||
e := uri.NewQueryEncoder(uri.QueryEncoderConfig{
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
})
|
||||
if err := func() error {
|
||||
if val, ok := params.Page.Get(); ok {
|
||||
return e.EncodeValue(conv.IntToString(val))
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "encode query")
|
||||
}
|
||||
q["page"] = e.Result()
|
||||
}
|
||||
{
|
||||
// Encode "itemsPerPage" parameter.
|
||||
e := uri.NewQueryEncoder(uri.QueryEncoderConfig{
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
})
|
||||
if err := func() error {
|
||||
if val, ok := params.ItemsPerPage.Get(); ok {
|
||||
return e.EncodeValue(conv.IntToString(val))
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "encode query")
|
||||
}
|
||||
q["itemsPerPage"] = e.Result()
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
r := ht.NewRequest(ctx, "GET", u, nil)
|
||||
defer ht.PutRequest(r)
|
||||
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
result, err := decodeListUsersResponse(resp, span)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ReadUsers invokes readUsers operation.
|
||||
//
|
||||
// Finds the Users with the requested ID and returns it.
|
||||
//
|
||||
// GET /users/{id}
|
||||
func (c *Client) ReadUsers(ctx context.Context, params ReadUsersParams) (res ReadUsersRes, err error) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("readUsers"),
|
||||
}
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, "ReadUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
c.errors.Add(ctx, 1, otelAttrs...)
|
||||
} else {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
c.requests.Add(ctx, 1, otelAttrs...)
|
||||
u := uri.Clone(c.serverURL)
|
||||
u.Path += "/users/"
|
||||
{
|
||||
// Encode "id" parameter.
|
||||
e := uri.NewPathEncoder(uri.PathEncoderConfig{
|
||||
Param: "id",
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
if err := func() error {
|
||||
return e.EncodeValue(conv.IntToString(params.ID))
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "encode path")
|
||||
}
|
||||
u.Path += e.Result()
|
||||
}
|
||||
|
||||
r := ht.NewRequest(ctx, "GET", u, nil)
|
||||
defer ht.PutRequest(r)
|
||||
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
result, err := decodeReadUsersResponse(resp, span)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// UpdateUsers invokes updateUsers operation.
|
||||
//
|
||||
// Updates a Users and persists changes to storage.
|
||||
//
|
||||
// PATCH /users/{id}
|
||||
func (c *Client) UpdateUsers(ctx context.Context, request UpdateUsersReq, params UpdateUsersParams) (res UpdateUsersRes, err error) {
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("updateUsers"),
|
||||
}
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, "UpdateUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
c.errors.Add(ctx, 1, otelAttrs...)
|
||||
} else {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
c.requests.Add(ctx, 1, otelAttrs...)
|
||||
var (
|
||||
contentType string
|
||||
reqBody io.Reader
|
||||
)
|
||||
contentType = "application/json"
|
||||
buf, err := encodeUpdateUsersRequestJSON(request, span)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer jx.PutEncoder(buf)
|
||||
reqBody = bytes.NewReader(buf.Bytes())
|
||||
|
||||
u := uri.Clone(c.serverURL)
|
||||
u.Path += "/users/"
|
||||
{
|
||||
// Encode "id" parameter.
|
||||
e := uri.NewPathEncoder(uri.PathEncoderConfig{
|
||||
Param: "id",
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
if err := func() error {
|
||||
return e.EncodeValue(conv.IntToString(params.ID))
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "encode path")
|
||||
}
|
||||
u.Path += e.Result()
|
||||
}
|
||||
|
||||
r := ht.NewRequest(ctx, "PATCH", u, reqBody)
|
||||
defer ht.PutRequest(r)
|
||||
|
||||
r.Header.Set("Content-Type", contentType)
|
||||
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
result, err := decodeUpdateUsersResponse(resp, span)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
71
ent/ogent/oas_defaults_gen.go
Normal file
71
ent/ogent/oas_defaults_gen.go
Normal file
@ -0,0 +1,71 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
390
ent/ogent/oas_handlers_gen.go
Normal file
390
ent/ogent/oas_handlers_gen.go
Normal file
@ -0,0 +1,390 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
// HandleCreateUsersRequest handles createUsers operation.
|
||||
//
|
||||
// POST /users
|
||||
func (s *Server) handleCreateUsersRequest(args [0]string, w http.ResponseWriter, r *http.Request) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("createUsers"),
|
||||
}
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), "CreateUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
s.requests.Add(ctx, 1, otelAttrs...)
|
||||
defer span.End()
|
||||
|
||||
var err error
|
||||
request, err := decodeCreateUsersRequest(r, span)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := s.h.CreateUsers(ctx, request)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Internal")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeCreateUsersResponse(response, w, span); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Response")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
return
|
||||
}
|
||||
span.SetStatus(codes.Ok, "Ok")
|
||||
elapsedDuration := time.Since(startTime)
|
||||
s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
|
||||
// HandleDeleteUsersRequest handles deleteUsers operation.
|
||||
//
|
||||
// DELETE /users/{id}
|
||||
func (s *Server) handleDeleteUsersRequest(args [1]string, w http.ResponseWriter, r *http.Request) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("deleteUsers"),
|
||||
}
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), "DeleteUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
s.requests.Add(ctx, 1, otelAttrs...)
|
||||
defer span.End()
|
||||
|
||||
var err error
|
||||
params, err := decodeDeleteUsersParams(args, r)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := s.h.DeleteUsers(ctx, params)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Internal")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeDeleteUsersResponse(response, w, span); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Response")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
return
|
||||
}
|
||||
span.SetStatus(codes.Ok, "Ok")
|
||||
elapsedDuration := time.Since(startTime)
|
||||
s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
|
||||
// HandleDrawDoneRequest handles drawDone operation.
|
||||
//
|
||||
// PUT /users/{id}/d
|
||||
func (s *Server) handleDrawDoneRequest(args [1]string, w http.ResponseWriter, r *http.Request) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("drawDone"),
|
||||
}
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), "DrawDone",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
s.requests.Add(ctx, 1, otelAttrs...)
|
||||
defer span.End()
|
||||
|
||||
var err error
|
||||
params, err := decodeDrawDoneParams(args, r)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := s.h.DrawDone(ctx, params)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Internal")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeDrawDoneResponse(response, w, span); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Response")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
return
|
||||
}
|
||||
span.SetStatus(codes.Ok, "Ok")
|
||||
elapsedDuration := time.Since(startTime)
|
||||
s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
|
||||
// HandleDrawStartRequest handles drawStart operation.
|
||||
//
|
||||
// PATCH /users/{id}/start
|
||||
func (s *Server) handleDrawStartRequest(args [1]string, w http.ResponseWriter, r *http.Request) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("drawStart"),
|
||||
}
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), "DrawStart",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
s.requests.Add(ctx, 1, otelAttrs...)
|
||||
defer span.End()
|
||||
|
||||
var err error
|
||||
params, err := decodeDrawStartParams(args, r)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := s.h.DrawStart(ctx, params)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Internal")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeDrawStartResponse(response, w, span); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Response")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
return
|
||||
}
|
||||
span.SetStatus(codes.Ok, "Ok")
|
||||
elapsedDuration := time.Since(startTime)
|
||||
s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
|
||||
// HandleListUsersRequest handles listUsers operation.
|
||||
//
|
||||
// GET /users
|
||||
func (s *Server) handleListUsersRequest(args [0]string, w http.ResponseWriter, r *http.Request) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("listUsers"),
|
||||
}
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), "ListUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
s.requests.Add(ctx, 1, otelAttrs...)
|
||||
defer span.End()
|
||||
|
||||
var err error
|
||||
params, err := decodeListUsersParams(args, r)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := s.h.ListUsers(ctx, params)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Internal")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeListUsersResponse(response, w, span); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Response")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
return
|
||||
}
|
||||
span.SetStatus(codes.Ok, "Ok")
|
||||
elapsedDuration := time.Since(startTime)
|
||||
s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
|
||||
// HandleReadUsersRequest handles readUsers operation.
|
||||
//
|
||||
// GET /users/{id}
|
||||
func (s *Server) handleReadUsersRequest(args [1]string, w http.ResponseWriter, r *http.Request) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("readUsers"),
|
||||
}
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), "ReadUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
s.requests.Add(ctx, 1, otelAttrs...)
|
||||
defer span.End()
|
||||
|
||||
var err error
|
||||
params, err := decodeReadUsersParams(args, r)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := s.h.ReadUsers(ctx, params)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Internal")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeReadUsersResponse(response, w, span); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Response")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
return
|
||||
}
|
||||
span.SetStatus(codes.Ok, "Ok")
|
||||
elapsedDuration := time.Since(startTime)
|
||||
s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
|
||||
// HandleUpdateUsersRequest handles updateUsers operation.
|
||||
//
|
||||
// PATCH /users/{id}
|
||||
func (s *Server) handleUpdateUsersRequest(args [1]string, w http.ResponseWriter, r *http.Request) {
|
||||
startTime := time.Now()
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("updateUsers"),
|
||||
}
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), "UpdateUsers",
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
s.requests.Add(ctx, 1, otelAttrs...)
|
||||
defer span.End()
|
||||
|
||||
var err error
|
||||
params, err := decodeUpdateUsersParams(args, r)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
request, err := decodeUpdateUsersRequest(r, span)
|
||||
if err != nil {
|
||||
s.badRequest(ctx, w, span, otelAttrs, err)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := s.h.UpdateUsers(ctx, request, params)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Internal")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeUpdateUsersResponse(response, w, span); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "Response")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
return
|
||||
}
|
||||
span.SetStatus(codes.Ok, "Ok")
|
||||
elapsedDuration := time.Since(startTime)
|
||||
s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
|
||||
}
|
||||
|
||||
func (s *Server) badRequest(ctx context.Context, w http.ResponseWriter, span trace.Span, otelAttrs []attribute.KeyValue, err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "BadRequest")
|
||||
s.errors.Add(ctx, 1, otelAttrs...)
|
||||
respondError(w, http.StatusBadRequest, err)
|
||||
}
|
||||
|
||||
func respondError(w http.ResponseWriter, code int, err error) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
data, writeErr := json.Marshal(struct {
|
||||
ErrorMessage string `json:"error_message"`
|
||||
}{
|
||||
ErrorMessage: err.Error(),
|
||||
})
|
||||
if writeErr == nil {
|
||||
w.Write(data)
|
||||
}
|
||||
}
|
22
ent/ogent/oas_interfaces_gen.go
Normal file
22
ent/ogent/oas_interfaces_gen.go
Normal file
@ -0,0 +1,22 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
package ogent
|
||||
|
||||
type CreateUsersRes interface {
|
||||
createUsersRes()
|
||||
}
|
||||
|
||||
type DeleteUsersRes interface {
|
||||
deleteUsersRes()
|
||||
}
|
||||
|
||||
type ListUsersRes interface {
|
||||
listUsersRes()
|
||||
}
|
||||
|
||||
type ReadUsersRes interface {
|
||||
readUsersRes()
|
||||
}
|
||||
|
||||
type UpdateUsersRes interface {
|
||||
updateUsersRes()
|
||||
}
|
2885
ent/ogent/oas_json_gen.go
Normal file
2885
ent/ogent/oas_json_gen.go
Normal file
File diff suppressed because it is too large
Load Diff
339
ent/ogent/oas_param_dec_gen.go
Normal file
339
ent/ogent/oas_param_dec_gen.go
Normal file
@ -0,0 +1,339 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
func decodeDeleteUsersParams(args [1]string, r *http.Request) (DeleteUsersParams, error) {
|
||||
var (
|
||||
params DeleteUsersParams
|
||||
)
|
||||
// Decode path: id.
|
||||
{
|
||||
param := args[0]
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
s, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, err
|
||||
}
|
||||
} else {
|
||||
return params, errors.New("path: id: not specified")
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func decodeDrawDoneParams(args [1]string, r *http.Request) (DrawDoneParams, error) {
|
||||
var (
|
||||
params DrawDoneParams
|
||||
)
|
||||
// Decode path: id.
|
||||
{
|
||||
param := args[0]
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
s, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, err
|
||||
}
|
||||
} else {
|
||||
return params, errors.New("path: id: not specified")
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func decodeDrawStartParams(args [1]string, r *http.Request) (DrawStartParams, error) {
|
||||
var (
|
||||
params DrawStartParams
|
||||
)
|
||||
// Decode path: id.
|
||||
{
|
||||
param := args[0]
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
s, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, err
|
||||
}
|
||||
} else {
|
||||
return params, errors.New("path: id: not specified")
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func decodeListUsersParams(args [0]string, r *http.Request) (ListUsersParams, error) {
|
||||
var (
|
||||
params ListUsersParams
|
||||
queryArgs = r.URL.Query()
|
||||
)
|
||||
// Decode query: page.
|
||||
{
|
||||
values, ok := queryArgs["page"]
|
||||
if ok {
|
||||
d := uri.NewQueryDecoder(uri.QueryDecoderConfig{
|
||||
Values: values,
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
var paramsDotPageVal int
|
||||
if err := func() error {
|
||||
s, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotPageVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Page.SetTo(paramsDotPageVal)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, errors.Wrap(err, "query: page: parse")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Decode query: itemsPerPage.
|
||||
{
|
||||
values, ok := queryArgs["itemsPerPage"]
|
||||
if ok {
|
||||
d := uri.NewQueryDecoder(uri.QueryDecoderConfig{
|
||||
Values: values,
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
var paramsDotItemsPerPageVal int
|
||||
if err := func() error {
|
||||
s, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotItemsPerPageVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.ItemsPerPage.SetTo(paramsDotItemsPerPageVal)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, errors.Wrap(err, "query: itemsPerPage: parse")
|
||||
}
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func decodeReadUsersParams(args [1]string, r *http.Request) (ReadUsersParams, error) {
|
||||
var (
|
||||
params ReadUsersParams
|
||||
)
|
||||
// Decode path: id.
|
||||
{
|
||||
param := args[0]
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
s, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, err
|
||||
}
|
||||
} else {
|
||||
return params, errors.New("path: id: not specified")
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func decodeUpdateUsersParams(args [1]string, r *http.Request) (UpdateUsersParams, error) {
|
||||
var (
|
||||
params UpdateUsersParams
|
||||
)
|
||||
// Decode path: id.
|
||||
{
|
||||
param := args[0]
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
s, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, err
|
||||
}
|
||||
} else {
|
||||
return params, errors.New("path: id: not specified")
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
101
ent/ogent/oas_param_gen.go
Normal file
101
ent/ogent/oas_param_gen.go
Normal file
@ -0,0 +1,101 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
type DeleteUsersParams struct {
|
||||
// ID of the Users.
|
||||
ID int
|
||||
}
|
||||
|
||||
type DrawDoneParams struct {
|
||||
ID int
|
||||
}
|
||||
|
||||
type DrawStartParams struct {
|
||||
ID int
|
||||
}
|
||||
|
||||
type ListUsersParams struct {
|
||||
// What page to render.
|
||||
Page OptInt
|
||||
// Item count to render per page.
|
||||
ItemsPerPage OptInt
|
||||
}
|
||||
|
||||
type ReadUsersParams struct {
|
||||
// ID of the Users.
|
||||
ID int
|
||||
}
|
||||
|
||||
type UpdateUsersParams struct {
|
||||
// ID of the Users.
|
||||
ID int
|
||||
}
|
159
ent/ogent/oas_req_dec_gen.go
Normal file
159
ent/ogent/oas_req_dec_gen.go
Normal file
@ -0,0 +1,159 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
func decodeCreateUsersRequest(r *http.Request, span trace.Span) (req CreateUsersReq, err error) {
|
||||
switch ct := r.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
var request CreateUsersReq
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
written, err := io.Copy(buf, r.Body)
|
||||
if err != nil {
|
||||
return req, err
|
||||
}
|
||||
|
||||
if written == 0 {
|
||||
return req, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, errors.Wrap(err, "decode CreateUsers:application/json request")
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, errors.Wrap(err, "validate CreateUsers request")
|
||||
}
|
||||
return request, nil
|
||||
default:
|
||||
return req, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeUpdateUsersRequest(r *http.Request, span trace.Span) (req UpdateUsersReq, err error) {
|
||||
switch ct := r.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
var request UpdateUsersReq
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
written, err := io.Copy(buf, r.Body)
|
||||
if err != nil {
|
||||
return req, err
|
||||
}
|
||||
|
||||
if written == 0 {
|
||||
return req, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, errors.Wrap(err, "decode UpdateUsers:application/json request")
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, errors.Wrap(err, "validate UpdateUsers request")
|
||||
}
|
||||
return request, nil
|
||||
default:
|
||||
return req, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
87
ent/ogent/oas_req_enc_gen.go
Normal file
87
ent/ogent/oas_req_enc_gen.go
Normal file
@ -0,0 +1,87 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
func encodeCreateUsersRequestJSON(req CreateUsersReq, span trace.Span) (data *jx.Encoder, err error) {
|
||||
e := jx.GetEncoder()
|
||||
|
||||
req.Encode(e)
|
||||
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func encodeUpdateUsersRequestJSON(req UpdateUsersReq, span trace.Span) (data *jx.Encoder, err error) {
|
||||
e := jx.GetEncoder()
|
||||
|
||||
req.Encode(e)
|
||||
|
||||
return e, nil
|
||||
}
|
747
ent/ogent/oas_res_dec_gen.go
Normal file
747
ent/ogent/oas_res_dec_gen.go
Normal file
@ -0,0 +1,747 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
func decodeCreateUsersResponse(resp *http.Response, span trace.Span) (res CreateUsersRes, err error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response UsersCreate
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 400:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R400
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 409:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R409
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 500:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R500
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
default:
|
||||
return res, validate.UnexpectedStatusCode(resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeDeleteUsersResponse(resp *http.Response, span trace.Span) (res DeleteUsersRes, err error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
return &DeleteUsersNoContent{}, nil
|
||||
case 400:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R400
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 404:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R404
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 409:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R409
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 500:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R500
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
default:
|
||||
return res, validate.UnexpectedStatusCode(resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeDrawDoneResponse(resp *http.Response, span trace.Span) (res DrawDoneNoContent, err error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
return DrawDoneNoContent{}, nil
|
||||
default:
|
||||
return res, validate.UnexpectedStatusCode(resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeDrawStartResponse(resp *http.Response, span trace.Span) (res DrawStartNoContent, err error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
return DrawStartNoContent{}, nil
|
||||
default:
|
||||
return res, validate.UnexpectedStatusCode(resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeListUsersResponse(resp *http.Response, span trace.Span) (res ListUsersRes, err error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response ListUsersOKApplicationJSON
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 400:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R400
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 404:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R404
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 409:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R409
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 500:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R500
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
default:
|
||||
return res, validate.UnexpectedStatusCode(resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeReadUsersResponse(resp *http.Response, span trace.Span) (res ReadUsersRes, err error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response UsersRead
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 400:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R400
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 404:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R404
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 409:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R409
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 500:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R500
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
default:
|
||||
return res, validate.UnexpectedStatusCode(resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeUpdateUsersResponse(resp *http.Response, span trace.Span) (res UpdateUsersRes, err error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response UsersUpdate
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 400:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R400
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 404:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R404
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 409:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R409
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 500:
|
||||
switch ct := resp.Header.Get("Content-Type"); ct {
|
||||
case "application/json":
|
||||
buf := getBuf()
|
||||
defer putBuf(buf)
|
||||
if _, err := io.Copy(buf, resp.Body); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
d := jx.GetDecoder()
|
||||
defer jx.PutDecoder(d)
|
||||
d.ResetBytes(buf.Bytes())
|
||||
|
||||
var response R500
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
default:
|
||||
return res, validate.UnexpectedStatusCode(resp.StatusCode)
|
||||
}
|
||||
}
|
395
ent/ogent/oas_res_enc_gen.go
Normal file
395
ent/ogent/oas_res_enc_gen.go
Normal file
@ -0,0 +1,395 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
func encodeCreateUsersResponse(response CreateUsersRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *UsersCreate:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(200)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R400:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R409:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(409)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R500:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("/users"+`: unexpected response type: %T`, response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeDeleteUsersResponse(response DeleteUsersRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *DeleteUsersNoContent:
|
||||
w.WriteHeader(204)
|
||||
return nil
|
||||
case *R400:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R404:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(404)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R409:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(409)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R500:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("/users/{id}"+`: unexpected response type: %T`, response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeDrawDoneResponse(response DrawDoneNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeDrawStartResponse(response DrawStartNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListUsersResponse(response ListUsersRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *ListUsersOKApplicationJSON:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(200)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R400:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R404:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(404)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R409:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(409)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R500:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("/users"+`: unexpected response type: %T`, response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeReadUsersResponse(response ReadUsersRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *UsersRead:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(200)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R400:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R404:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(404)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R409:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(409)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R500:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("/users/{id}"+`: unexpected response type: %T`, response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeUpdateUsersResponse(response UpdateUsersRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *UsersUpdate:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(200)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R400:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R404:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(404)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R409:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(409)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
case *R500:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
e := jx.GetEncoder()
|
||||
defer jx.PutEncoder(e)
|
||||
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("/users/{id}"+`: unexpected response type: %T`, response)
|
||||
}
|
||||
}
|
467
ent/ogent/oas_router_gen.go
Normal file
467
ent/ogent/oas_router_gen.go
Normal file
@ -0,0 +1,467 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
s.cfg.NotFound(w, r)
|
||||
}
|
||||
|
||||
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
|
||||
// calling handler that matches the path or returning not found error.
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
elem := r.URL.Path
|
||||
if len(elem) == 0 {
|
||||
s.notFound(w, r)
|
||||
return
|
||||
}
|
||||
args := [1]string{}
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch r.Method {
|
||||
case "DELETE":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users/"
|
||||
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Leaf parameter
|
||||
args[0] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: DeleteUsers
|
||||
s.handleDeleteUsersRequest([1]string{
|
||||
args[0],
|
||||
}, w, r)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
case "GET":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users"
|
||||
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
s.handleListUsersRequest([0]string{}, w, r)
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Leaf parameter
|
||||
args[0] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: ReadUsers
|
||||
s.handleReadUsersRequest([1]string{
|
||||
args[0],
|
||||
}, w, r)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
case "PATCH":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users/"
|
||||
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
s.handleUpdateUsersRequest([1]string{
|
||||
args[0],
|
||||
}, w, r)
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/start"
|
||||
if l := len("/start"); len(elem) >= l && elem[0:l] == "/start" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: DrawStart
|
||||
s.handleDrawStartRequest([1]string{
|
||||
args[0],
|
||||
}, w, r)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
case "POST":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users"
|
||||
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: CreateUsers
|
||||
s.handleCreateUsersRequest([0]string{}, w, r)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
case "PUT":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users/"
|
||||
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/d"
|
||||
if l := len("/d"); len(elem) >= l && elem[0:l] == "/d" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: DrawDone
|
||||
s.handleDrawDoneRequest([1]string{
|
||||
args[0],
|
||||
}, w, r)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.notFound(w, r)
|
||||
}
|
||||
|
||||
// Route is route object.
|
||||
type Route struct {
|
||||
name string
|
||||
count int
|
||||
args [1]string
|
||||
}
|
||||
|
||||
// OperationID returns OpenAPI operationId.
|
||||
func (r Route) OperationID() string {
|
||||
return r.name
|
||||
}
|
||||
|
||||
// Args returns parsed arguments.
|
||||
func (r Route) Args() []string {
|
||||
return r.args[:r.count]
|
||||
}
|
||||
|
||||
// FindRoute finds Route for given method and path.
|
||||
func (s *Server) FindRoute(method, path string) (r Route, _ bool) {
|
||||
var (
|
||||
args = [1]string{}
|
||||
elem = path
|
||||
)
|
||||
r.args = args
|
||||
if elem == "" {
|
||||
return r, false
|
||||
}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch method {
|
||||
case "DELETE":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users/"
|
||||
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Leaf parameter
|
||||
args[0] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: DeleteUsers
|
||||
r.name = "DeleteUsers"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
case "GET":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users"
|
||||
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
r.name = "ListUsers"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Leaf parameter
|
||||
args[0] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: ReadUsers
|
||||
r.name = "ReadUsers"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
}
|
||||
case "PATCH":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users/"
|
||||
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
r.name = "UpdateUsers"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/start"
|
||||
if l := len("/start"); len(elem) >= l && elem[0:l] == "/start" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: DrawStart
|
||||
r.name = "DrawStart"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
}
|
||||
case "POST":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users"
|
||||
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: CreateUsers
|
||||
r.name = "CreateUsers"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
case "PUT":
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/users/"
|
||||
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/d"
|
||||
if l := len("/d"); len(elem) >= l && elem[0:l] == "/d" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf: DrawDone
|
||||
r.name = "DrawDone"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return r, false
|
||||
}
|
497
ent/ogent/oas_schemas_gen.go
Normal file
497
ent/ogent/oas_schemas_gen.go
Normal file
@ -0,0 +1,497 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
type CreateUsersReq struct {
|
||||
User string "json:\"user\""
|
||||
Chara OptString "json:\"chara\""
|
||||
Skill OptInt "json:\"skill\""
|
||||
Hp OptInt "json:\"hp\""
|
||||
Attack OptInt "json:\"attack\""
|
||||
Defense OptInt "json:\"defense\""
|
||||
Critical OptInt "json:\"critical\""
|
||||
Battle OptInt "json:\"battle\""
|
||||
Win OptInt "json:\"win\""
|
||||
Day OptInt "json:\"day\""
|
||||
Percentage OptFloat64 "json:\"percentage\""
|
||||
Limit OptBool "json:\"limit\""
|
||||
Status OptString "json:\"status\""
|
||||
Comment OptString "json:\"comment\""
|
||||
CreatedAt OptDateTime "json:\"created_at\""
|
||||
Next OptString "json:\"next\""
|
||||
UpdatedAt OptDateTime "json:\"updated_at\""
|
||||
URL OptString "json:\"url\""
|
||||
}
|
||||
|
||||
// DeleteUsersNoContent is response for DeleteUsers operation.
|
||||
type DeleteUsersNoContent struct{}
|
||||
|
||||
func (*DeleteUsersNoContent) deleteUsersRes() {}
|
||||
|
||||
// DrawDoneNoContent is response for DrawDone operation.
|
||||
type DrawDoneNoContent struct{}
|
||||
|
||||
// DrawStartNoContent is response for DrawStart operation.
|
||||
type DrawStartNoContent struct{}
|
||||
|
||||
type ListUsersOKApplicationJSON []UsersList
|
||||
|
||||
func (ListUsersOKApplicationJSON) listUsersRes() {}
|
||||
|
||||
// NewOptBool returns new OptBool with value set to v.
|
||||
func NewOptBool(v bool) OptBool {
|
||||
return OptBool{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptBool is optional bool.
|
||||
type OptBool struct {
|
||||
Value bool
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptBool was set.
|
||||
func (o OptBool) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptBool) Reset() {
|
||||
var v bool
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptBool) SetTo(v bool) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptBool) Get() (v bool, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptBool) Or(d bool) bool {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptDateTime returns new OptDateTime with value set to v.
|
||||
func NewOptDateTime(v time.Time) OptDateTime {
|
||||
return OptDateTime{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptDateTime is optional time.Time.
|
||||
type OptDateTime struct {
|
||||
Value time.Time
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptDateTime was set.
|
||||
func (o OptDateTime) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptDateTime) Reset() {
|
||||
var v time.Time
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptDateTime) SetTo(v time.Time) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptDateTime) Get() (v time.Time, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptDateTime) Or(d time.Time) time.Time {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptFloat64 returns new OptFloat64 with value set to v.
|
||||
func NewOptFloat64(v float64) OptFloat64 {
|
||||
return OptFloat64{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptFloat64 is optional float64.
|
||||
type OptFloat64 struct {
|
||||
Value float64
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptFloat64 was set.
|
||||
func (o OptFloat64) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptFloat64) Reset() {
|
||||
var v float64
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptFloat64) SetTo(v float64) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptFloat64) Get() (v float64, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptFloat64) Or(d float64) float64 {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptInt returns new OptInt with value set to v.
|
||||
func NewOptInt(v int) OptInt {
|
||||
return OptInt{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptInt is optional int.
|
||||
type OptInt struct {
|
||||
Value int
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptInt was set.
|
||||
func (o OptInt) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptInt) Reset() {
|
||||
var v int
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptInt) SetTo(v int) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptInt) Get() (v int, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptInt) Or(d int) int {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptString returns new OptString with value set to v.
|
||||
func NewOptString(v string) OptString {
|
||||
return OptString{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptString is optional string.
|
||||
type OptString struct {
|
||||
Value string
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptString was set.
|
||||
func (o OptString) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptString) Reset() {
|
||||
var v string
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptString) SetTo(v string) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptString) Get() (v string, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptString) Or(d string) string {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
type R400 struct {
|
||||
Code int "json:\"code\""
|
||||
Status string "json:\"status\""
|
||||
Errors jx.Raw "json:\"errors\""
|
||||
}
|
||||
|
||||
func (*R400) createUsersRes() {}
|
||||
func (*R400) deleteUsersRes() {}
|
||||
func (*R400) listUsersRes() {}
|
||||
func (*R400) readUsersRes() {}
|
||||
func (*R400) updateUsersRes() {}
|
||||
|
||||
type R404 struct {
|
||||
Code int "json:\"code\""
|
||||
Status string "json:\"status\""
|
||||
Errors jx.Raw "json:\"errors\""
|
||||
}
|
||||
|
||||
func (*R404) deleteUsersRes() {}
|
||||
func (*R404) listUsersRes() {}
|
||||
func (*R404) readUsersRes() {}
|
||||
func (*R404) updateUsersRes() {}
|
||||
|
||||
type R409 struct {
|
||||
Code int "json:\"code\""
|
||||
Status string "json:\"status\""
|
||||
Errors jx.Raw "json:\"errors\""
|
||||
}
|
||||
|
||||
func (*R409) createUsersRes() {}
|
||||
func (*R409) deleteUsersRes() {}
|
||||
func (*R409) listUsersRes() {}
|
||||
func (*R409) readUsersRes() {}
|
||||
func (*R409) updateUsersRes() {}
|
||||
|
||||
type R500 struct {
|
||||
Code int "json:\"code\""
|
||||
Status string "json:\"status\""
|
||||
Errors jx.Raw "json:\"errors\""
|
||||
}
|
||||
|
||||
func (*R500) createUsersRes() {}
|
||||
func (*R500) deleteUsersRes() {}
|
||||
func (*R500) listUsersRes() {}
|
||||
func (*R500) readUsersRes() {}
|
||||
func (*R500) updateUsersRes() {}
|
||||
|
||||
type UpdateUsersReq struct {
|
||||
Hp OptInt "json:\"hp\""
|
||||
Attack OptInt "json:\"attack\""
|
||||
Defense OptInt "json:\"defense\""
|
||||
Critical OptInt "json:\"critical\""
|
||||
Battle OptInt "json:\"battle\""
|
||||
Win OptInt "json:\"win\""
|
||||
Day OptInt "json:\"day\""
|
||||
Percentage OptFloat64 "json:\"percentage\""
|
||||
Limit OptBool "json:\"limit\""
|
||||
Comment OptString "json:\"comment\""
|
||||
Next OptString "json:\"next\""
|
||||
UpdatedAt OptDateTime "json:\"updated_at\""
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/UsersCreate
|
||||
type UsersCreate struct {
|
||||
ID int "json:\"id\""
|
||||
User string "json:\"user\""
|
||||
Chara OptString "json:\"chara\""
|
||||
Skill OptInt "json:\"skill\""
|
||||
Hp OptInt "json:\"hp\""
|
||||
Attack OptInt "json:\"attack\""
|
||||
Defense OptInt "json:\"defense\""
|
||||
Critical OptInt "json:\"critical\""
|
||||
Battle OptInt "json:\"battle\""
|
||||
Win OptInt "json:\"win\""
|
||||
Day OptInt "json:\"day\""
|
||||
Percentage OptFloat64 "json:\"percentage\""
|
||||
Limit OptBool "json:\"limit\""
|
||||
Status OptString "json:\"status\""
|
||||
Comment OptString "json:\"comment\""
|
||||
CreatedAt OptDateTime "json:\"created_at\""
|
||||
Next OptString "json:\"next\""
|
||||
UpdatedAt OptDateTime "json:\"updated_at\""
|
||||
URL OptString "json:\"url\""
|
||||
}
|
||||
|
||||
func (*UsersCreate) createUsersRes() {}
|
||||
|
||||
// Ref: #/components/schemas/UsersList
|
||||
type UsersList struct {
|
||||
ID int "json:\"id\""
|
||||
User string "json:\"user\""
|
||||
Chara OptString "json:\"chara\""
|
||||
Skill OptInt "json:\"skill\""
|
||||
Hp OptInt "json:\"hp\""
|
||||
Attack OptInt "json:\"attack\""
|
||||
Defense OptInt "json:\"defense\""
|
||||
Critical OptInt "json:\"critical\""
|
||||
Battle OptInt "json:\"battle\""
|
||||
Win OptInt "json:\"win\""
|
||||
Day OptInt "json:\"day\""
|
||||
Percentage OptFloat64 "json:\"percentage\""
|
||||
Limit OptBool "json:\"limit\""
|
||||
Status OptString "json:\"status\""
|
||||
Comment OptString "json:\"comment\""
|
||||
CreatedAt OptDateTime "json:\"created_at\""
|
||||
Next OptString "json:\"next\""
|
||||
UpdatedAt OptDateTime "json:\"updated_at\""
|
||||
URL OptString "json:\"url\""
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/UsersRead
|
||||
type UsersRead struct {
|
||||
ID int "json:\"id\""
|
||||
User string "json:\"user\""
|
||||
Chara OptString "json:\"chara\""
|
||||
Skill OptInt "json:\"skill\""
|
||||
Hp OptInt "json:\"hp\""
|
||||
Attack OptInt "json:\"attack\""
|
||||
Defense OptInt "json:\"defense\""
|
||||
Critical OptInt "json:\"critical\""
|
||||
Battle OptInt "json:\"battle\""
|
||||
Win OptInt "json:\"win\""
|
||||
Day OptInt "json:\"day\""
|
||||
Percentage OptFloat64 "json:\"percentage\""
|
||||
Limit OptBool "json:\"limit\""
|
||||
Status OptString "json:\"status\""
|
||||
Comment OptString "json:\"comment\""
|
||||
CreatedAt OptDateTime "json:\"created_at\""
|
||||
Next OptString "json:\"next\""
|
||||
UpdatedAt OptDateTime "json:\"updated_at\""
|
||||
URL OptString "json:\"url\""
|
||||
}
|
||||
|
||||
func (*UsersRead) readUsersRes() {}
|
||||
|
||||
// Ref: #/components/schemas/UsersUpdate
|
||||
type UsersUpdate struct {
|
||||
ID int "json:\"id\""
|
||||
User string "json:\"user\""
|
||||
Chara OptString "json:\"chara\""
|
||||
Skill OptInt "json:\"skill\""
|
||||
Hp OptInt "json:\"hp\""
|
||||
Attack OptInt "json:\"attack\""
|
||||
Defense OptInt "json:\"defense\""
|
||||
Critical OptInt "json:\"critical\""
|
||||
Battle OptInt "json:\"battle\""
|
||||
Win OptInt "json:\"win\""
|
||||
Day OptInt "json:\"day\""
|
||||
Percentage OptFloat64 "json:\"percentage\""
|
||||
Limit OptBool "json:\"limit\""
|
||||
Status OptString "json:\"status\""
|
||||
Comment OptString "json:\"comment\""
|
||||
CreatedAt OptDateTime "json:\"created_at\""
|
||||
Next OptString "json:\"next\""
|
||||
UpdatedAt OptDateTime "json:\"updated_at\""
|
||||
URL OptString "json:\"url\""
|
||||
}
|
||||
|
||||
func (*UsersUpdate) updateUsersRes() {}
|
71
ent/ogent/oas_security_gen.go
Normal file
71
ent/ogent/oas_security_gen.go
Normal file
@ -0,0 +1,71 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
142
ent/ogent/oas_server_gen.go
Normal file
142
ent/ogent/oas_server_gen.go
Normal file
@ -0,0 +1,142 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
// Handler handles operations described by OpenAPI v3 specification.
|
||||
type Handler interface {
|
||||
// CreateUsers implements createUsers operation.
|
||||
//
|
||||
// Creates a new Users and persists it to storage.
|
||||
//
|
||||
// POST /users
|
||||
CreateUsers(ctx context.Context, req CreateUsersReq) (CreateUsersRes, error)
|
||||
// DeleteUsers implements deleteUsers operation.
|
||||
//
|
||||
// Deletes the Users with the requested ID.
|
||||
//
|
||||
// DELETE /users/{id}
|
||||
DeleteUsers(ctx context.Context, params DeleteUsersParams) (DeleteUsersRes, error)
|
||||
// DrawDone implements drawDone operation.
|
||||
//
|
||||
// PUT /users/{id}/d
|
||||
DrawDone(ctx context.Context, params DrawDoneParams) (DrawDoneNoContent, error)
|
||||
// DrawStart implements drawStart operation.
|
||||
//
|
||||
// PATCH /users/{id}/start
|
||||
DrawStart(ctx context.Context, params DrawStartParams) (DrawStartNoContent, error)
|
||||
// ListUsers implements listUsers operation.
|
||||
//
|
||||
// List Users.
|
||||
//
|
||||
// GET /users
|
||||
ListUsers(ctx context.Context, params ListUsersParams) (ListUsersRes, error)
|
||||
// ReadUsers implements readUsers operation.
|
||||
//
|
||||
// Finds the Users with the requested ID and returns it.
|
||||
//
|
||||
// GET /users/{id}
|
||||
ReadUsers(ctx context.Context, params ReadUsersParams) (ReadUsersRes, error)
|
||||
// UpdateUsers implements updateUsers operation.
|
||||
//
|
||||
// Updates a Users and persists changes to storage.
|
||||
//
|
||||
// PATCH /users/{id}
|
||||
UpdateUsers(ctx context.Context, req UpdateUsersReq, params UpdateUsersParams) (UpdateUsersRes, error)
|
||||
}
|
||||
|
||||
// Server implements http server based on OpenAPI v3 specification and
|
||||
// calls Handler to handle requests.
|
||||
type Server struct {
|
||||
h Handler
|
||||
cfg config
|
||||
|
||||
requests metric.Int64Counter
|
||||
errors metric.Int64Counter
|
||||
duration metric.Int64Histogram
|
||||
}
|
||||
|
||||
func NewServer(h Handler, opts ...Option) (*Server, error) {
|
||||
s := &Server{
|
||||
h: h,
|
||||
cfg: newConfig(opts...),
|
||||
}
|
||||
var err error
|
||||
if s.requests, err = s.cfg.Meter.NewInt64Counter(otelogen.ServerRequestCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.errors, err = s.cfg.Meter.NewInt64Counter(otelogen.ServerErrorsCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.duration, err = s.cfg.Meter.NewInt64Histogram(otelogen.ServerDuration); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
135
ent/ogent/oas_unimplemented_gen.go
Normal file
135
ent/ogent/oas_unimplemented_gen.go
Normal file
@ -0,0 +1,135 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
var _ Handler = UnimplementedHandler{}
|
||||
|
||||
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
|
||||
type UnimplementedHandler struct{}
|
||||
|
||||
// CreateUsers implements createUsers operation.
|
||||
//
|
||||
// Creates a new Users and persists it to storage.
|
||||
//
|
||||
// POST /users
|
||||
func (UnimplementedHandler) CreateUsers(ctx context.Context, req CreateUsersReq) (r CreateUsersRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// DeleteUsers implements deleteUsers operation.
|
||||
//
|
||||
// Deletes the Users with the requested ID.
|
||||
//
|
||||
// DELETE /users/{id}
|
||||
func (UnimplementedHandler) DeleteUsers(ctx context.Context, params DeleteUsersParams) (r DeleteUsersRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// DrawDone implements drawDone operation.
|
||||
//
|
||||
// PUT /users/{id}/d
|
||||
func (UnimplementedHandler) DrawDone(ctx context.Context, params DrawDoneParams) (r DrawDoneNoContent, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// DrawStart implements drawStart operation.
|
||||
//
|
||||
// PATCH /users/{id}/start
|
||||
func (UnimplementedHandler) DrawStart(ctx context.Context, params DrawStartParams) (r DrawStartNoContent, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListUsers implements listUsers operation.
|
||||
//
|
||||
// List Users.
|
||||
//
|
||||
// GET /users
|
||||
func (UnimplementedHandler) ListUsers(ctx context.Context, params ListUsersParams) (r ListUsersRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ReadUsers implements readUsers operation.
|
||||
//
|
||||
// Finds the Users with the requested ID and returns it.
|
||||
//
|
||||
// GET /users/{id}
|
||||
func (UnimplementedHandler) ReadUsers(ctx context.Context, params ReadUsersParams) (r ReadUsersRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// UpdateUsers implements updateUsers operation.
|
||||
//
|
||||
// Updates a Users and persists changes to storage.
|
||||
//
|
||||
// PATCH /users/{id}
|
||||
func (UnimplementedHandler) UpdateUsers(ctx context.Context, req UpdateUsersReq, params UpdateUsersParams) (r UpdateUsersRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
252
ent/ogent/oas_validators_gen.go
Normal file
252
ent/ogent/oas_validators_gen.go
Normal file
@ -0,0 +1,252 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/json"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// No-op definition for keeping imports.
|
||||
var (
|
||||
_ = context.Background()
|
||||
_ = fmt.Stringer(nil)
|
||||
_ = strings.Builder{}
|
||||
_ = errors.Is
|
||||
_ = sort.Ints
|
||||
_ = http.MethodGet
|
||||
_ = io.Copy
|
||||
_ = json.Marshal
|
||||
_ = bytes.NewReader
|
||||
_ = strconv.ParseInt
|
||||
_ = time.Time{}
|
||||
_ = conv.ToInt32
|
||||
_ = uuid.UUID{}
|
||||
_ = uri.PathEncoder{}
|
||||
_ = url.URL{}
|
||||
_ = math.Mod
|
||||
_ = bits.LeadingZeros64
|
||||
_ = big.Rat{}
|
||||
_ = validate.Int{}
|
||||
_ = ht.NewRequest
|
||||
_ = net.IP{}
|
||||
_ = otelogen.Version
|
||||
_ = attribute.KeyValue{}
|
||||
_ = trace.TraceIDFromHex
|
||||
_ = otel.GetTracerProvider
|
||||
_ = metric.NewNoopMeterProvider
|
||||
_ = regexp.MustCompile
|
||||
_ = jx.Null
|
||||
_ = sync.Pool{}
|
||||
_ = codes.Unset
|
||||
)
|
||||
|
||||
func (s CreateUsersReq) Validate() error {
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Percentage.Set {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "percentage",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s ListUsersOKApplicationJSON) Validate() error {
|
||||
if s == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s UpdateUsersReq) Validate() error {
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Percentage.Set {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "percentage",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s UsersCreate) Validate() error {
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Percentage.Set {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "percentage",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s UsersList) Validate() error {
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Percentage.Set {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "percentage",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s UsersRead) Validate() error {
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Percentage.Set {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "percentage",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s UsersUpdate) Validate() error {
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Percentage.Set {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "percentage",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
274
ent/ogent/ogent.go
Normal file
274
ent/ogent/ogent.go
Normal file
@ -0,0 +1,274 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"t/ent"
|
||||
"t/ent/users"
|
||||
|
||||
"github.com/go-faster/jx"
|
||||
)
|
||||
|
||||
// OgentHandler implements the ogen generated Handler interface and uses Ent as data layer.
|
||||
type OgentHandler struct {
|
||||
client *ent.Client
|
||||
}
|
||||
|
||||
// NewOgentHandler returns a new OgentHandler.
|
||||
func NewOgentHandler(c *ent.Client) *OgentHandler { return &OgentHandler{c} }
|
||||
|
||||
// rawError renders err as json string.
|
||||
func rawError(err error) jx.Raw {
|
||||
var e jx.Encoder
|
||||
e.Str(err.Error())
|
||||
return e.Bytes()
|
||||
}
|
||||
|
||||
// CreateUsers handles POST /users-slice requests.
|
||||
func (h *OgentHandler) CreateUsers(ctx context.Context, req CreateUsersReq) (CreateUsersRes, error) {
|
||||
b := h.client.Users.Create()
|
||||
// Add all fields.
|
||||
b.SetUser(req.User)
|
||||
if v, ok := req.Chara.Get(); ok {
|
||||
b.SetChara(v)
|
||||
}
|
||||
if v, ok := req.Skill.Get(); ok {
|
||||
b.SetSkill(v)
|
||||
}
|
||||
if v, ok := req.Hp.Get(); ok {
|
||||
b.SetHp(v)
|
||||
}
|
||||
if v, ok := req.Attack.Get(); ok {
|
||||
b.SetAttack(v)
|
||||
}
|
||||
if v, ok := req.Defense.Get(); ok {
|
||||
b.SetDefense(v)
|
||||
}
|
||||
if v, ok := req.Critical.Get(); ok {
|
||||
b.SetCritical(v)
|
||||
}
|
||||
if v, ok := req.Battle.Get(); ok {
|
||||
b.SetBattle(v)
|
||||
}
|
||||
if v, ok := req.Win.Get(); ok {
|
||||
b.SetWin(v)
|
||||
}
|
||||
if v, ok := req.Day.Get(); ok {
|
||||
b.SetDay(v)
|
||||
}
|
||||
if v, ok := req.Percentage.Get(); ok {
|
||||
b.SetPercentage(v)
|
||||
}
|
||||
if v, ok := req.Limit.Get(); ok {
|
||||
b.SetLimit(v)
|
||||
}
|
||||
if v, ok := req.Status.Get(); ok {
|
||||
b.SetStatus(v)
|
||||
}
|
||||
if v, ok := req.Comment.Get(); ok {
|
||||
b.SetComment(v)
|
||||
}
|
||||
if v, ok := req.CreatedAt.Get(); ok {
|
||||
b.SetCreatedAt(v)
|
||||
}
|
||||
if v, ok := req.Next.Get(); ok {
|
||||
b.SetNext(v)
|
||||
}
|
||||
if v, ok := req.UpdatedAt.Get(); ok {
|
||||
b.SetUpdatedAt(v)
|
||||
}
|
||||
if v, ok := req.URL.Get(); ok {
|
||||
b.SetURL(v)
|
||||
}
|
||||
// Add all edges.
|
||||
// Persist to storage.
|
||||
e, err := b.Save(ctx)
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotSingular(err):
|
||||
return &R409{
|
||||
Code: http.StatusConflict,
|
||||
Status: http.StatusText(http.StatusConflict),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
case ent.IsConstraintError(err):
|
||||
return &R409{
|
||||
Code: http.StatusConflict,
|
||||
Status: http.StatusText(http.StatusConflict),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
default:
|
||||
// Let the server handle the error.
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// Reload the entity to attach all eager-loaded edges.
|
||||
q := h.client.Users.Query().Where(users.ID(e.ID))
|
||||
e, err = q.Only(ctx)
|
||||
if err != nil {
|
||||
// This should never happen.
|
||||
return nil, err
|
||||
}
|
||||
return NewUsersCreate(e), nil
|
||||
}
|
||||
|
||||
// ReadUsers handles GET /users-slice/{id} requests.
|
||||
func (h *OgentHandler) ReadUsers(ctx context.Context, params ReadUsersParams) (ReadUsersRes, error) {
|
||||
q := h.client.Users.Query().Where(users.IDEQ(params.ID))
|
||||
e, err := q.Only(ctx)
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
return &R404{
|
||||
Code: http.StatusNotFound,
|
||||
Status: http.StatusText(http.StatusNotFound),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
case ent.IsNotSingular(err):
|
||||
return &R409{
|
||||
Code: http.StatusConflict,
|
||||
Status: http.StatusText(http.StatusConflict),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
default:
|
||||
// Let the server handle the error.
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return NewUsersRead(e), nil
|
||||
}
|
||||
|
||||
// UpdateUsers handles PATCH /users-slice/{id} requests.
|
||||
func (h *OgentHandler) UpdateUsers(ctx context.Context, req UpdateUsersReq, params UpdateUsersParams) (UpdateUsersRes, error) {
|
||||
b := h.client.Users.UpdateOneID(params.ID)
|
||||
// Add all fields.
|
||||
if v, ok := req.Hp.Get(); ok {
|
||||
b.SetHp(v)
|
||||
}
|
||||
if v, ok := req.Attack.Get(); ok {
|
||||
b.SetAttack(v)
|
||||
}
|
||||
if v, ok := req.Defense.Get(); ok {
|
||||
b.SetDefense(v)
|
||||
}
|
||||
if v, ok := req.Critical.Get(); ok {
|
||||
b.SetCritical(v)
|
||||
}
|
||||
if v, ok := req.Battle.Get(); ok {
|
||||
b.SetBattle(v)
|
||||
}
|
||||
if v, ok := req.Win.Get(); ok {
|
||||
b.SetWin(v)
|
||||
}
|
||||
if v, ok := req.Day.Get(); ok {
|
||||
b.SetDay(v)
|
||||
}
|
||||
if v, ok := req.Percentage.Get(); ok {
|
||||
b.SetPercentage(v)
|
||||
}
|
||||
if v, ok := req.Limit.Get(); ok {
|
||||
b.SetLimit(v)
|
||||
}
|
||||
if v, ok := req.Comment.Get(); ok {
|
||||
b.SetComment(v)
|
||||
}
|
||||
if v, ok := req.Next.Get(); ok {
|
||||
b.SetNext(v)
|
||||
}
|
||||
if v, ok := req.UpdatedAt.Get(); ok {
|
||||
b.SetUpdatedAt(v)
|
||||
}
|
||||
// Add all edges.
|
||||
// Persist to storage.
|
||||
e, err := b.Save(ctx)
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
return &R404{
|
||||
Code: http.StatusNotFound,
|
||||
Status: http.StatusText(http.StatusNotFound),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
case ent.IsConstraintError(err):
|
||||
return &R409{
|
||||
Code: http.StatusConflict,
|
||||
Status: http.StatusText(http.StatusConflict),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
default:
|
||||
// Let the server handle the error.
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// Reload the entity to attach all eager-loaded edges.
|
||||
q := h.client.Users.Query().Where(users.ID(e.ID))
|
||||
e, err = q.Only(ctx)
|
||||
if err != nil {
|
||||
// This should never happen.
|
||||
return nil, err
|
||||
}
|
||||
return NewUsersUpdate(e), nil
|
||||
}
|
||||
|
||||
// DeleteUsers handles DELETE /users-slice/{id} requests.
|
||||
func (h *OgentHandler) DeleteUsers(ctx context.Context, params DeleteUsersParams) (DeleteUsersRes, error) {
|
||||
err := h.client.Users.DeleteOneID(params.ID).Exec(ctx)
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
return &R404{
|
||||
Code: http.StatusNotFound,
|
||||
Status: http.StatusText(http.StatusNotFound),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
case ent.IsConstraintError(err):
|
||||
return &R409{
|
||||
Code: http.StatusConflict,
|
||||
Status: http.StatusText(http.StatusConflict),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
default:
|
||||
// Let the server handle the error.
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return new(DeleteUsersNoContent), nil
|
||||
|
||||
}
|
||||
|
||||
// ListUsers handles GET /users-slice requests.
|
||||
func (h *OgentHandler) ListUsers(ctx context.Context, params ListUsersParams) (ListUsersRes, error) {
|
||||
q := h.client.Users.Query()
|
||||
page := 1
|
||||
if v, ok := params.Page.Get(); ok {
|
||||
page = v
|
||||
}
|
||||
itemsPerPage := 30
|
||||
if v, ok := params.ItemsPerPage.Get(); ok {
|
||||
itemsPerPage = v
|
||||
}
|
||||
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(ctx)
|
||||
if err != nil {
|
||||
switch {
|
||||
case ent.IsNotFound(err):
|
||||
return &R404{
|
||||
Code: http.StatusNotFound,
|
||||
Status: http.StatusText(http.StatusNotFound),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
case ent.IsNotSingular(err):
|
||||
return &R409{
|
||||
Code: http.StatusConflict,
|
||||
Status: http.StatusText(http.StatusConflict),
|
||||
Errors: rawError(err),
|
||||
}, nil
|
||||
default:
|
||||
// Let the server handle the error.
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return ListUsersOKApplicationJSON(NewUsersLists(es)), nil
|
||||
}
|
185
ent/ogent/responses.go
Normal file
185
ent/ogent/responses.go
Normal file
@ -0,0 +1,185 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ogent
|
||||
|
||||
import "t/ent"
|
||||
|
||||
func NewUsersCreate(e *ent.Users) *UsersCreate {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &UsersCreate{
|
||||
ID: e.ID,
|
||||
User: e.User,
|
||||
Chara: NewOptString(e.Chara),
|
||||
Skill: NewOptInt(e.Skill),
|
||||
Hp: NewOptInt(e.Hp),
|
||||
Attack: NewOptInt(e.Attack),
|
||||
Defense: NewOptInt(e.Defense),
|
||||
Critical: NewOptInt(e.Critical),
|
||||
Battle: NewOptInt(e.Battle),
|
||||
Win: NewOptInt(e.Win),
|
||||
Day: NewOptInt(e.Day),
|
||||
Percentage: NewOptFloat64(e.Percentage),
|
||||
Limit: NewOptBool(e.Limit),
|
||||
Status: NewOptString(e.Status),
|
||||
Comment: NewOptString(e.Comment),
|
||||
CreatedAt: NewOptDateTime(e.CreatedAt),
|
||||
Next: NewOptString(e.Next),
|
||||
UpdatedAt: NewOptDateTime(e.UpdatedAt),
|
||||
URL: NewOptString(e.URL),
|
||||
}
|
||||
}
|
||||
|
||||
func NewUsersCreates(es []*ent.Users) []UsersCreate {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make([]UsersCreate, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewUsersCreate(e).Elem()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (u *UsersCreate) Elem() UsersCreate {
|
||||
if u != nil {
|
||||
return UsersCreate{}
|
||||
}
|
||||
return *u
|
||||
}
|
||||
|
||||
func NewUsersList(e *ent.Users) *UsersList {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &UsersList{
|
||||
ID: e.ID,
|
||||
User: e.User,
|
||||
Chara: NewOptString(e.Chara),
|
||||
Skill: NewOptInt(e.Skill),
|
||||
Hp: NewOptInt(e.Hp),
|
||||
Attack: NewOptInt(e.Attack),
|
||||
Defense: NewOptInt(e.Defense),
|
||||
Critical: NewOptInt(e.Critical),
|
||||
Battle: NewOptInt(e.Battle),
|
||||
Win: NewOptInt(e.Win),
|
||||
Day: NewOptInt(e.Day),
|
||||
Percentage: NewOptFloat64(e.Percentage),
|
||||
Limit: NewOptBool(e.Limit),
|
||||
Status: NewOptString(e.Status),
|
||||
Comment: NewOptString(e.Comment),
|
||||
CreatedAt: NewOptDateTime(e.CreatedAt),
|
||||
Next: NewOptString(e.Next),
|
||||
UpdatedAt: NewOptDateTime(e.UpdatedAt),
|
||||
URL: NewOptString(e.URL),
|
||||
}
|
||||
}
|
||||
|
||||
func NewUsersLists(es []*ent.Users) []UsersList {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make([]UsersList, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewUsersList(e).Elem()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (u *UsersList) Elem() UsersList {
|
||||
if u != nil {
|
||||
return UsersList{}
|
||||
}
|
||||
return *u
|
||||
}
|
||||
|
||||
func NewUsersRead(e *ent.Users) *UsersRead {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &UsersRead{
|
||||
ID: e.ID,
|
||||
User: e.User,
|
||||
Chara: NewOptString(e.Chara),
|
||||
Skill: NewOptInt(e.Skill),
|
||||
Hp: NewOptInt(e.Hp),
|
||||
Attack: NewOptInt(e.Attack),
|
||||
Defense: NewOptInt(e.Defense),
|
||||
Critical: NewOptInt(e.Critical),
|
||||
Battle: NewOptInt(e.Battle),
|
||||
Win: NewOptInt(e.Win),
|
||||
Day: NewOptInt(e.Day),
|
||||
Percentage: NewOptFloat64(e.Percentage),
|
||||
Limit: NewOptBool(e.Limit),
|
||||
Status: NewOptString(e.Status),
|
||||
Comment: NewOptString(e.Comment),
|
||||
CreatedAt: NewOptDateTime(e.CreatedAt),
|
||||
Next: NewOptString(e.Next),
|
||||
UpdatedAt: NewOptDateTime(e.UpdatedAt),
|
||||
URL: NewOptString(e.URL),
|
||||
}
|
||||
}
|
||||
|
||||
func NewUsersReads(es []*ent.Users) []UsersRead {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make([]UsersRead, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewUsersRead(e).Elem()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (u *UsersRead) Elem() UsersRead {
|
||||
if u != nil {
|
||||
return UsersRead{}
|
||||
}
|
||||
return *u
|
||||
}
|
||||
|
||||
func NewUsersUpdate(e *ent.Users) *UsersUpdate {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &UsersUpdate{
|
||||
ID: e.ID,
|
||||
User: e.User,
|
||||
Chara: NewOptString(e.Chara),
|
||||
Skill: NewOptInt(e.Skill),
|
||||
Hp: NewOptInt(e.Hp),
|
||||
Attack: NewOptInt(e.Attack),
|
||||
Defense: NewOptInt(e.Defense),
|
||||
Critical: NewOptInt(e.Critical),
|
||||
Battle: NewOptInt(e.Battle),
|
||||
Win: NewOptInt(e.Win),
|
||||
Day: NewOptInt(e.Day),
|
||||
Percentage: NewOptFloat64(e.Percentage),
|
||||
Limit: NewOptBool(e.Limit),
|
||||
Status: NewOptString(e.Status),
|
||||
Comment: NewOptString(e.Comment),
|
||||
CreatedAt: NewOptDateTime(e.CreatedAt),
|
||||
Next: NewOptString(e.Next),
|
||||
UpdatedAt: NewOptDateTime(e.UpdatedAt),
|
||||
URL: NewOptString(e.URL),
|
||||
}
|
||||
}
|
||||
|
||||
func NewUsersUpdates(es []*ent.Users) []UsersUpdate {
|
||||
if len(es) == 0 {
|
||||
return nil
|
||||
}
|
||||
r := make([]UsersUpdate, len(es))
|
||||
for i, e := range es {
|
||||
r[i] = NewUsersUpdate(e).Elem()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (u *UsersUpdate) Elem() UsersUpdate {
|
||||
if u != nil {
|
||||
return UsersUpdate{}
|
||||
}
|
||||
return *u
|
||||
}
|
858
ent/openapi.json
Normal file
858
ent/openapi.json
Normal file
@ -0,0 +1,858 @@
|
||||
{
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "Ent Schema API",
|
||||
"description": "This is an auto generated API description made out of an Ent schema definition",
|
||||
"version": "0.1.0"
|
||||
},
|
||||
"paths": {
|
||||
"/users": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"summary": "List Users",
|
||||
"description": "List Users.",
|
||||
"operationId": "listUsers",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "page",
|
||||
"in": "query",
|
||||
"description": "what page to render",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "itemsPerPage",
|
||||
"in": "query",
|
||||
"description": "item count to render per page",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "result Users list",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/UsersList"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/400"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/404"
|
||||
},
|
||||
"409": {
|
||||
"$ref": "#/components/responses/409"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/500"
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"summary": "Create a new Users",
|
||||
"description": "Creates a new Users and persists it to storage.",
|
||||
"operationId": "createUsers",
|
||||
"requestBody": {
|
||||
"description": "Users to create",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"chara": {
|
||||
"type": "string"
|
||||
},
|
||||
"skill": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hp": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attack": {
|
||||
"type": "integer"
|
||||
},
|
||||
"defense": {
|
||||
"type": "integer"
|
||||
},
|
||||
"critical": {
|
||||
"type": "integer"
|
||||
},
|
||||
"battle": {
|
||||
"type": "integer"
|
||||
},
|
||||
"win": {
|
||||
"type": "integer"
|
||||
},
|
||||
"day": {
|
||||
"type": "integer"
|
||||
},
|
||||
"percentage": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"limit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"next": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"user"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Users created",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UsersCreate"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/400"
|
||||
},
|
||||
"409": {
|
||||
"$ref": "#/components/responses/409"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/500"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/users/{id}": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"summary": "Find a Users by ID",
|
||||
"description": "Finds the Users with the requested ID and returns it.",
|
||||
"operationId": "readUsers",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"description": "ID of the Users",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Users with requested ID was found",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UsersRead"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/400"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/404"
|
||||
},
|
||||
"409": {
|
||||
"$ref": "#/components/responses/409"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/500"
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"summary": "Deletes a Users by ID",
|
||||
"description": "Deletes the Users with the requested ID.",
|
||||
"operationId": "deleteUsers",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"description": "ID of the Users",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "Users with requested ID was deleted"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/400"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/404"
|
||||
},
|
||||
"409": {
|
||||
"$ref": "#/components/responses/409"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/500"
|
||||
}
|
||||
}
|
||||
},
|
||||
"patch": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"summary": "Updates a Users",
|
||||
"description": "Updates a Users and persists changes to storage.",
|
||||
"operationId": "updateUsers",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"description": "ID of the Users",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"description": "Users properties to update",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"hp": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attack": {
|
||||
"type": "integer"
|
||||
},
|
||||
"defense": {
|
||||
"type": "integer"
|
||||
},
|
||||
"critical": {
|
||||
"type": "integer"
|
||||
},
|
||||
"battle": {
|
||||
"type": "integer"
|
||||
},
|
||||
"win": {
|
||||
"type": "integer"
|
||||
},
|
||||
"day": {
|
||||
"type": "integer"
|
||||
},
|
||||
"percentage": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"limit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"next": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Users updated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UsersUpdate"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/400"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/404"
|
||||
},
|
||||
"409": {
|
||||
"$ref": "#/components/responses/409"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/500"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/users/{id}/d": {
|
||||
"description": "Start an draw as done",
|
||||
"put": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"summary": "Draws a card item as done.",
|
||||
"operationId": "drawDone",
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "Item marked as done"
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"/users/{id}/start": {
|
||||
"description": "Start an draw as done",
|
||||
"patch": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"summary": "Draws a card item as done.",
|
||||
"operationId": "drawStart",
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "Item marked as done"
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"schemas": {
|
||||
"Users": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"chara": {
|
||||
"type": "string"
|
||||
},
|
||||
"skill": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hp": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attack": {
|
||||
"type": "integer"
|
||||
},
|
||||
"defense": {
|
||||
"type": "integer"
|
||||
},
|
||||
"critical": {
|
||||
"type": "integer"
|
||||
},
|
||||
"battle": {
|
||||
"type": "integer"
|
||||
},
|
||||
"win": {
|
||||
"type": "integer"
|
||||
},
|
||||
"day": {
|
||||
"type": "integer"
|
||||
},
|
||||
"percentage": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"limit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"next": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"user"
|
||||
]
|
||||
},
|
||||
"UsersCreate": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"chara": {
|
||||
"type": "string"
|
||||
},
|
||||
"skill": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hp": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attack": {
|
||||
"type": "integer"
|
||||
},
|
||||
"defense": {
|
||||
"type": "integer"
|
||||
},
|
||||
"critical": {
|
||||
"type": "integer"
|
||||
},
|
||||
"battle": {
|
||||
"type": "integer"
|
||||
},
|
||||
"win": {
|
||||
"type": "integer"
|
||||
},
|
||||
"day": {
|
||||
"type": "integer"
|
||||
},
|
||||
"percentage": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"limit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"next": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"user"
|
||||
]
|
||||
},
|
||||
"UsersList": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"chara": {
|
||||
"type": "string"
|
||||
},
|
||||
"skill": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hp": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attack": {
|
||||
"type": "integer"
|
||||
},
|
||||
"defense": {
|
||||
"type": "integer"
|
||||
},
|
||||
"critical": {
|
||||
"type": "integer"
|
||||
},
|
||||
"battle": {
|
||||
"type": "integer"
|
||||
},
|
||||
"win": {
|
||||
"type": "integer"
|
||||
},
|
||||
"day": {
|
||||
"type": "integer"
|
||||
},
|
||||
"percentage": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"limit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"next": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"user"
|
||||
]
|
||||
},
|
||||
"UsersRead": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"chara": {
|
||||
"type": "string"
|
||||
},
|
||||
"skill": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hp": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attack": {
|
||||
"type": "integer"
|
||||
},
|
||||
"defense": {
|
||||
"type": "integer"
|
||||
},
|
||||
"critical": {
|
||||
"type": "integer"
|
||||
},
|
||||
"battle": {
|
||||
"type": "integer"
|
||||
},
|
||||
"win": {
|
||||
"type": "integer"
|
||||
},
|
||||
"day": {
|
||||
"type": "integer"
|
||||
},
|
||||
"percentage": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"limit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"next": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"user"
|
||||
]
|
||||
},
|
||||
"UsersUpdate": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"chara": {
|
||||
"type": "string"
|
||||
},
|
||||
"skill": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hp": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attack": {
|
||||
"type": "integer"
|
||||
},
|
||||
"defense": {
|
||||
"type": "integer"
|
||||
},
|
||||
"critical": {
|
||||
"type": "integer"
|
||||
},
|
||||
"battle": {
|
||||
"type": "integer"
|
||||
},
|
||||
"win": {
|
||||
"type": "integer"
|
||||
},
|
||||
"day": {
|
||||
"type": "integer"
|
||||
},
|
||||
"percentage": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"limit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"next": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"user"
|
||||
]
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"400": {
|
||||
"description": "invalid input, data invalid",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "integer"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"errors": {}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"status"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "insufficient permissions",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "integer"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"errors": {}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"status"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "resource not found",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "integer"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"errors": {}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"status"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "conflicting resources",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "integer"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"errors": {}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"status"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "unexpected error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "integer"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"errors": {}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"status"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
10
ent/predicate/predicate.go
Normal file
10
ent/predicate/predicate.go
Normal file
@ -0,0 +1,10 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package predicate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Users is the predicate function for users builders.
|
||||
type Users func(*sql.Selector)
|
104
ent/runtime.go
Normal file
104
ent/runtime.go
Normal file
@ -0,0 +1,104 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"t/ent/schema"
|
||||
"t/ent/users"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The init function reads all schema descriptors with runtime code
|
||||
// (default values, validators, hooks and policies) and stitches it
|
||||
// to their package variables.
|
||||
func init() {
|
||||
usersFields := schema.Users{}.Fields()
|
||||
_ = usersFields
|
||||
// usersDescUser is the schema descriptor for user field.
|
||||
usersDescUser := usersFields[0].Descriptor()
|
||||
// users.UserValidator is a validator for the "user" field. It is called by the builders before save.
|
||||
users.UserValidator = func() func(string) error {
|
||||
validators := usersDescUser.Validators
|
||||
fns := [...]func(string) error{
|
||||
validators[0].(func(string) error),
|
||||
validators[1].(func(string) error),
|
||||
validators[2].(func(string) error),
|
||||
}
|
||||
return func(user string) error {
|
||||
for _, fn := range fns {
|
||||
if err := fn(user); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}()
|
||||
// usersDescChara is the schema descriptor for chara field.
|
||||
usersDescChara := usersFields[1].Descriptor()
|
||||
// users.DefaultChara holds the default value on creation for the chara field.
|
||||
users.DefaultChara = usersDescChara.Default.(string)
|
||||
// usersDescSkill is the schema descriptor for skill field.
|
||||
usersDescSkill := usersFields[2].Descriptor()
|
||||
// users.DefaultSkill holds the default value on creation for the skill field.
|
||||
users.DefaultSkill = usersDescSkill.Default.(int)
|
||||
// usersDescHp is the schema descriptor for hp field.
|
||||
usersDescHp := usersFields[3].Descriptor()
|
||||
// users.DefaultHp holds the default value on creation for the hp field.
|
||||
users.DefaultHp = usersDescHp.Default.(int)
|
||||
// usersDescAttack is the schema descriptor for attack field.
|
||||
usersDescAttack := usersFields[4].Descriptor()
|
||||
// users.DefaultAttack holds the default value on creation for the attack field.
|
||||
users.DefaultAttack = usersDescAttack.Default.(int)
|
||||
// usersDescDefense is the schema descriptor for defense field.
|
||||
usersDescDefense := usersFields[5].Descriptor()
|
||||
// users.DefaultDefense holds the default value on creation for the defense field.
|
||||
users.DefaultDefense = usersDescDefense.Default.(int)
|
||||
// usersDescCritical is the schema descriptor for critical field.
|
||||
usersDescCritical := usersFields[6].Descriptor()
|
||||
// users.DefaultCritical holds the default value on creation for the critical field.
|
||||
users.DefaultCritical = usersDescCritical.Default.(int)
|
||||
// usersDescBattle is the schema descriptor for battle field.
|
||||
usersDescBattle := usersFields[7].Descriptor()
|
||||
// users.DefaultBattle holds the default value on creation for the battle field.
|
||||
users.DefaultBattle = usersDescBattle.Default.(int)
|
||||
// usersDescWin is the schema descriptor for win field.
|
||||
usersDescWin := usersFields[8].Descriptor()
|
||||
// users.DefaultWin holds the default value on creation for the win field.
|
||||
users.DefaultWin = usersDescWin.Default.(int)
|
||||
// usersDescDay is the schema descriptor for day field.
|
||||
usersDescDay := usersFields[9].Descriptor()
|
||||
// users.DefaultDay holds the default value on creation for the day field.
|
||||
users.DefaultDay = usersDescDay.Default.(int)
|
||||
// usersDescPercentage is the schema descriptor for percentage field.
|
||||
usersDescPercentage := usersFields[10].Descriptor()
|
||||
// users.DefaultPercentage holds the default value on creation for the percentage field.
|
||||
users.DefaultPercentage = usersDescPercentage.Default.(float64)
|
||||
// usersDescLimit is the schema descriptor for limit field.
|
||||
usersDescLimit := usersFields[11].Descriptor()
|
||||
// users.DefaultLimit holds the default value on creation for the limit field.
|
||||
users.DefaultLimit = usersDescLimit.Default.(bool)
|
||||
// usersDescStatus is the schema descriptor for status field.
|
||||
usersDescStatus := usersFields[12].Descriptor()
|
||||
// users.DefaultStatus holds the default value on creation for the status field.
|
||||
users.DefaultStatus = usersDescStatus.Default.(string)
|
||||
// usersDescComment is the schema descriptor for comment field.
|
||||
usersDescComment := usersFields[13].Descriptor()
|
||||
// users.DefaultComment holds the default value on creation for the comment field.
|
||||
users.DefaultComment = usersDescComment.Default.(string)
|
||||
// usersDescCreatedAt is the schema descriptor for created_at field.
|
||||
usersDescCreatedAt := usersFields[14].Descriptor()
|
||||
// users.DefaultCreatedAt holds the default value on creation for the created_at field.
|
||||
users.DefaultCreatedAt = usersDescCreatedAt.Default.(func() time.Time)
|
||||
// usersDescNext is the schema descriptor for next field.
|
||||
usersDescNext := usersFields[15].Descriptor()
|
||||
// users.DefaultNext holds the default value on creation for the next field.
|
||||
users.DefaultNext = usersDescNext.Default.(string)
|
||||
// usersDescUpdatedAt is the schema descriptor for updated_at field.
|
||||
usersDescUpdatedAt := usersFields[16].Descriptor()
|
||||
// users.DefaultUpdatedAt holds the default value on creation for the updated_at field.
|
||||
users.DefaultUpdatedAt = usersDescUpdatedAt.Default.(func() time.Time)
|
||||
// usersDescURL is the schema descriptor for url field.
|
||||
usersDescURL := usersFields[17].Descriptor()
|
||||
// users.DefaultURL holds the default value on creation for the url field.
|
||||
users.DefaultURL = usersDescURL.Default.(string)
|
||||
}
|
10
ent/runtime/runtime.go
Normal file
10
ent/runtime/runtime.go
Normal file
@ -0,0 +1,10 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package runtime
|
||||
|
||||
// The schema-stitching logic is generated in t/ent/runtime.go
|
||||
|
||||
const (
|
||||
Version = "v0.10.0" // Version of ent codegen.
|
||||
Sum = "h1:9cBomE1fh+WX34DPYQL7tDNAIvhKa3tXvwxuLyhYCMo=" // Sum of ent codegen.
|
||||
)
|
172
ent/schema/users.go
Normal file
172
ent/schema/users.go
Normal file
@ -0,0 +1,172 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"time"
|
||||
"regexp"
|
||||
"entgo.io/ent"
|
||||
"math/rand"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/kyokomi/lottery"
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
func Random(i int) (l int){
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
l = rand.Intn(20)
|
||||
for l == 0 {
|
||||
l = rand.Intn(20)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Kira(i int) (l bool){
|
||||
lot := lottery.New(rand.New(rand.NewSource(time.Now().UnixNano())))
|
||||
if lot.Lot(i) {
|
||||
l = true
|
||||
} else {
|
||||
l = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var jst,err = time.LoadLocation("Asia/Tokyo")
|
||||
|
||||
var a = Random(4)
|
||||
var d = Random(20)
|
||||
var h = Random(20)
|
||||
var k = Random(20)
|
||||
var s = Random(20)
|
||||
var c = Random(20)
|
||||
var battle = 2
|
||||
|
||||
func StatusR()(status string){
|
||||
if d == 1 {
|
||||
var status = "super"
|
||||
return status
|
||||
} else {
|
||||
var status = "normal"
|
||||
return status
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CharaR()(chara string){
|
||||
if a == 1 {
|
||||
var chara = "drai"
|
||||
return chara
|
||||
} else if a == 2 {
|
||||
var chara = "octkat"
|
||||
return chara
|
||||
} else if a == 3 {
|
||||
var chara = "kyosuke"
|
||||
return chara
|
||||
} else {
|
||||
var chara = "ponta"
|
||||
return chara
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Nextime() (tt string){
|
||||
t := time.Now().Add(time.Hour * 24 * 1).In(jst)
|
||||
tt = t.Format("20060102")
|
||||
return
|
||||
}
|
||||
|
||||
func (Users) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
|
||||
field.String("user").
|
||||
NotEmpty().
|
||||
Immutable().
|
||||
MaxLen(7).
|
||||
Match(regexp.MustCompile("[a-z]+$")).
|
||||
Unique(),
|
||||
|
||||
field.String("chara").
|
||||
Immutable().
|
||||
Default(CharaR()).
|
||||
Optional(),
|
||||
|
||||
field.Int("skill").
|
||||
Immutable().
|
||||
Optional().
|
||||
Default(k),
|
||||
|
||||
field.Int("hp").
|
||||
Optional().
|
||||
Default(h),
|
||||
|
||||
field.Int("attack").
|
||||
Optional().
|
||||
Default(a),
|
||||
|
||||
field.Int("defense").
|
||||
Optional().
|
||||
Default(d),
|
||||
|
||||
field.Int("critical").
|
||||
Optional().
|
||||
Default(c),
|
||||
|
||||
field.Int("battle").
|
||||
Optional().
|
||||
Default(1),
|
||||
|
||||
field.Int("win").
|
||||
Optional().
|
||||
Default(0),
|
||||
|
||||
field.Int("day").
|
||||
Optional().
|
||||
Default(0),
|
||||
|
||||
field.Float("percentage").
|
||||
Optional().
|
||||
Default(0),
|
||||
|
||||
field.Bool("limit").
|
||||
Optional().
|
||||
Default(false),
|
||||
|
||||
field.String("status").
|
||||
Immutable().
|
||||
Optional().
|
||||
Default(StatusR()),
|
||||
|
||||
field.String("comment").
|
||||
Optional().
|
||||
Default(""),
|
||||
|
||||
field.Time("created_at").
|
||||
Immutable().
|
||||
Optional().
|
||||
Default(func() time.Time {
|
||||
return time.Now().In(jst)
|
||||
}),
|
||||
|
||||
field.String("next").
|
||||
Default(Nextime()).
|
||||
Optional(),
|
||||
|
||||
field.Time("updated_at").
|
||||
Optional().
|
||||
Default(func() time.Time {
|
||||
return time.Now().In(jst)
|
||||
}),
|
||||
|
||||
field.String("url").
|
||||
Immutable().
|
||||
Optional().
|
||||
Default("https://syui.cf/api"),
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (Users) Edges() []ent.Edge {
|
||||
return []ent.Edge{}
|
||||
}
|
||||
|
210
ent/tx.go
Normal file
210
ent/tx.go
Normal file
@ -0,0 +1,210 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
)
|
||||
|
||||
// Tx is a transactional client that is created by calling Client.Tx().
|
||||
type Tx struct {
|
||||
config
|
||||
// Users is the client for interacting with the Users builders.
|
||||
Users *UsersClient
|
||||
|
||||
// lazily loaded.
|
||||
client *Client
|
||||
clientOnce sync.Once
|
||||
|
||||
// completion callbacks.
|
||||
mu sync.Mutex
|
||||
onCommit []CommitHook
|
||||
onRollback []RollbackHook
|
||||
|
||||
// ctx lives for the life of the transaction. It is
|
||||
// the same context used by the underlying connection.
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
type (
|
||||
// Committer is the interface that wraps the Commit method.
|
||||
Committer interface {
|
||||
Commit(context.Context, *Tx) error
|
||||
}
|
||||
|
||||
// The CommitFunc type is an adapter to allow the use of ordinary
|
||||
// function as a Committer. If f is a function with the appropriate
|
||||
// signature, CommitFunc(f) is a Committer that calls f.
|
||||
CommitFunc func(context.Context, *Tx) error
|
||||
|
||||
// CommitHook defines the "commit middleware". A function that gets a Committer
|
||||
// and returns a Committer. For example:
|
||||
//
|
||||
// hook := func(next ent.Committer) ent.Committer {
|
||||
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
|
||||
// // Do some stuff before.
|
||||
// if err := next.Commit(ctx, tx); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// // Do some stuff after.
|
||||
// return nil
|
||||
// })
|
||||
// }
|
||||
//
|
||||
CommitHook func(Committer) Committer
|
||||
)
|
||||
|
||||
// Commit calls f(ctx, m).
|
||||
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
|
||||
return f(ctx, tx)
|
||||
}
|
||||
|
||||
// Commit commits the transaction.
|
||||
func (tx *Tx) Commit() error {
|
||||
txDriver := tx.config.driver.(*txDriver)
|
||||
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
|
||||
return txDriver.tx.Commit()
|
||||
})
|
||||
tx.mu.Lock()
|
||||
hooks := append([]CommitHook(nil), tx.onCommit...)
|
||||
tx.mu.Unlock()
|
||||
for i := len(hooks) - 1; i >= 0; i-- {
|
||||
fn = hooks[i](fn)
|
||||
}
|
||||
return fn.Commit(tx.ctx, tx)
|
||||
}
|
||||
|
||||
// OnCommit adds a hook to call on commit.
|
||||
func (tx *Tx) OnCommit(f CommitHook) {
|
||||
tx.mu.Lock()
|
||||
defer tx.mu.Unlock()
|
||||
tx.onCommit = append(tx.onCommit, f)
|
||||
}
|
||||
|
||||
type (
|
||||
// Rollbacker is the interface that wraps the Rollback method.
|
||||
Rollbacker interface {
|
||||
Rollback(context.Context, *Tx) error
|
||||
}
|
||||
|
||||
// The RollbackFunc type is an adapter to allow the use of ordinary
|
||||
// function as a Rollbacker. If f is a function with the appropriate
|
||||
// signature, RollbackFunc(f) is a Rollbacker that calls f.
|
||||
RollbackFunc func(context.Context, *Tx) error
|
||||
|
||||
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
|
||||
// and returns a Rollbacker. For example:
|
||||
//
|
||||
// hook := func(next ent.Rollbacker) ent.Rollbacker {
|
||||
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
|
||||
// // Do some stuff before.
|
||||
// if err := next.Rollback(ctx, tx); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// // Do some stuff after.
|
||||
// return nil
|
||||
// })
|
||||
// }
|
||||
//
|
||||
RollbackHook func(Rollbacker) Rollbacker
|
||||
)
|
||||
|
||||
// Rollback calls f(ctx, m).
|
||||
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
|
||||
return f(ctx, tx)
|
||||
}
|
||||
|
||||
// Rollback rollbacks the transaction.
|
||||
func (tx *Tx) Rollback() error {
|
||||
txDriver := tx.config.driver.(*txDriver)
|
||||
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
|
||||
return txDriver.tx.Rollback()
|
||||
})
|
||||
tx.mu.Lock()
|
||||
hooks := append([]RollbackHook(nil), tx.onRollback...)
|
||||
tx.mu.Unlock()
|
||||
for i := len(hooks) - 1; i >= 0; i-- {
|
||||
fn = hooks[i](fn)
|
||||
}
|
||||
return fn.Rollback(tx.ctx, tx)
|
||||
}
|
||||
|
||||
// OnRollback adds a hook to call on rollback.
|
||||
func (tx *Tx) OnRollback(f RollbackHook) {
|
||||
tx.mu.Lock()
|
||||
defer tx.mu.Unlock()
|
||||
tx.onRollback = append(tx.onRollback, f)
|
||||
}
|
||||
|
||||
// Client returns a Client that binds to current transaction.
|
||||
func (tx *Tx) Client() *Client {
|
||||
tx.clientOnce.Do(func() {
|
||||
tx.client = &Client{config: tx.config}
|
||||
tx.client.init()
|
||||
})
|
||||
return tx.client
|
||||
}
|
||||
|
||||
func (tx *Tx) init() {
|
||||
tx.Users = NewUsersClient(tx.config)
|
||||
}
|
||||
|
||||
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
|
||||
// The idea is to support transactions without adding any extra code to the builders.
|
||||
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
|
||||
// Commit and Rollback are nop for the internal builders and the user must call one
|
||||
// of them in order to commit or rollback the transaction.
|
||||
//
|
||||
// If a closed transaction is embedded in one of the generated entities, and the entity
|
||||
// applies a query, for example: Users.QueryXXX(), the query will be executed
|
||||
// through the driver which created this transaction.
|
||||
//
|
||||
// Note that txDriver is not goroutine safe.
|
||||
type txDriver struct {
|
||||
// the driver we started the transaction from.
|
||||
drv dialect.Driver
|
||||
// tx is the underlying transaction.
|
||||
tx dialect.Tx
|
||||
}
|
||||
|
||||
// newTx creates a new transactional driver.
|
||||
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
|
||||
tx, err := drv.Tx(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &txDriver{tx: tx, drv: drv}, nil
|
||||
}
|
||||
|
||||
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
|
||||
// from the internal builders. Should be called only by the internal builders.
|
||||
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
|
||||
|
||||
// Dialect returns the dialect of the driver we started the transaction from.
|
||||
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
|
||||
|
||||
// Close is a nop close.
|
||||
func (*txDriver) Close() error { return nil }
|
||||
|
||||
// Commit is a nop commit for the internal builders.
|
||||
// User must call `Tx.Commit` in order to commit the transaction.
|
||||
func (*txDriver) Commit() error { return nil }
|
||||
|
||||
// Rollback is a nop rollback for the internal builders.
|
||||
// User must call `Tx.Rollback` in order to rollback the transaction.
|
||||
func (*txDriver) Rollback() error { return nil }
|
||||
|
||||
// Exec calls tx.Exec.
|
||||
func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error {
|
||||
return tx.tx.Exec(ctx, query, args, v)
|
||||
}
|
||||
|
||||
// Query calls tx.Query.
|
||||
func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error {
|
||||
return tx.tx.Query(ctx, query, args, v)
|
||||
}
|
||||
|
||||
var _ dialect.Driver = (*txDriver)(nil)
|
276
ent/users.go
Normal file
276
ent/users.go
Normal file
@ -0,0 +1,276 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"t/ent/users"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Users is the model entity for the Users schema.
|
||||
type Users struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// User holds the value of the "user" field.
|
||||
User string `json:"user,omitempty"`
|
||||
// Chara holds the value of the "chara" field.
|
||||
Chara string `json:"chara,omitempty"`
|
||||
// Skill holds the value of the "skill" field.
|
||||
Skill int `json:"skill,omitempty"`
|
||||
// Hp holds the value of the "hp" field.
|
||||
Hp int `json:"hp,omitempty"`
|
||||
// Attack holds the value of the "attack" field.
|
||||
Attack int `json:"attack,omitempty"`
|
||||
// Defense holds the value of the "defense" field.
|
||||
Defense int `json:"defense,omitempty"`
|
||||
// Critical holds the value of the "critical" field.
|
||||
Critical int `json:"critical,omitempty"`
|
||||
// Battle holds the value of the "battle" field.
|
||||
Battle int `json:"battle,omitempty"`
|
||||
// Win holds the value of the "win" field.
|
||||
Win int `json:"win,omitempty"`
|
||||
// Day holds the value of the "day" field.
|
||||
Day int `json:"day,omitempty"`
|
||||
// Percentage holds the value of the "percentage" field.
|
||||
Percentage float64 `json:"percentage,omitempty"`
|
||||
// Limit holds the value of the "limit" field.
|
||||
Limit bool `json:"limit,omitempty"`
|
||||
// Status holds the value of the "status" field.
|
||||
Status string `json:"status,omitempty"`
|
||||
// Comment holds the value of the "comment" field.
|
||||
Comment string `json:"comment,omitempty"`
|
||||
// CreatedAt holds the value of the "created_at" field.
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// Next holds the value of the "next" field.
|
||||
Next string `json:"next,omitempty"`
|
||||
// UpdatedAt holds the value of the "updated_at" field.
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
// URL holds the value of the "url" field.
|
||||
URL string `json:"url,omitempty"`
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*Users) scanValues(columns []string) ([]interface{}, error) {
|
||||
values := make([]interface{}, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case users.FieldLimit:
|
||||
values[i] = new(sql.NullBool)
|
||||
case users.FieldPercentage:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case users.FieldID, users.FieldSkill, users.FieldHp, users.FieldAttack, users.FieldDefense, users.FieldCritical, users.FieldBattle, users.FieldWin, users.FieldDay:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case users.FieldUser, users.FieldChara, users.FieldStatus, users.FieldComment, users.FieldNext, users.FieldURL:
|
||||
values[i] = new(sql.NullString)
|
||||
case users.FieldCreatedAt, users.FieldUpdatedAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected column %q for type Users", columns[i])
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the Users fields.
|
||||
func (u *Users) assignValues(columns []string, values []interface{}) error {
|
||||
if m, n := len(values), len(columns); m < n {
|
||||
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
|
||||
}
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case users.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
u.ID = int(value.Int64)
|
||||
case users.FieldUser:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user", values[i])
|
||||
} else if value.Valid {
|
||||
u.User = value.String
|
||||
}
|
||||
case users.FieldChara:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field chara", values[i])
|
||||
} else if value.Valid {
|
||||
u.Chara = value.String
|
||||
}
|
||||
case users.FieldSkill:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field skill", values[i])
|
||||
} else if value.Valid {
|
||||
u.Skill = int(value.Int64)
|
||||
}
|
||||
case users.FieldHp:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field hp", values[i])
|
||||
} else if value.Valid {
|
||||
u.Hp = int(value.Int64)
|
||||
}
|
||||
case users.FieldAttack:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field attack", values[i])
|
||||
} else if value.Valid {
|
||||
u.Attack = int(value.Int64)
|
||||
}
|
||||
case users.FieldDefense:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field defense", values[i])
|
||||
} else if value.Valid {
|
||||
u.Defense = int(value.Int64)
|
||||
}
|
||||
case users.FieldCritical:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field critical", values[i])
|
||||
} else if value.Valid {
|
||||
u.Critical = int(value.Int64)
|
||||
}
|
||||
case users.FieldBattle:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field battle", values[i])
|
||||
} else if value.Valid {
|
||||
u.Battle = int(value.Int64)
|
||||
}
|
||||
case users.FieldWin:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field win", values[i])
|
||||
} else if value.Valid {
|
||||
u.Win = int(value.Int64)
|
||||
}
|
||||
case users.FieldDay:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field day", values[i])
|
||||
} else if value.Valid {
|
||||
u.Day = int(value.Int64)
|
||||
}
|
||||
case users.FieldPercentage:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field percentage", values[i])
|
||||
} else if value.Valid {
|
||||
u.Percentage = value.Float64
|
||||
}
|
||||
case users.FieldLimit:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field limit", values[i])
|
||||
} else if value.Valid {
|
||||
u.Limit = value.Bool
|
||||
}
|
||||
case users.FieldStatus:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field status", values[i])
|
||||
} else if value.Valid {
|
||||
u.Status = value.String
|
||||
}
|
||||
case users.FieldComment:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field comment", values[i])
|
||||
} else if value.Valid {
|
||||
u.Comment = value.String
|
||||
}
|
||||
case users.FieldCreatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field created_at", values[i])
|
||||
} else if value.Valid {
|
||||
u.CreatedAt = value.Time
|
||||
}
|
||||
case users.FieldNext:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field next", values[i])
|
||||
} else if value.Valid {
|
||||
u.Next = value.String
|
||||
}
|
||||
case users.FieldUpdatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
|
||||
} else if value.Valid {
|
||||
u.UpdatedAt = value.Time
|
||||
}
|
||||
case users.FieldURL:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field url", values[i])
|
||||
} else if value.Valid {
|
||||
u.URL = value.String
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Users.
|
||||
// Note that you need to call Users.Unwrap() before calling this method if this Users
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (u *Users) Update() *UsersUpdateOne {
|
||||
return (&UsersClient{config: u.config}).UpdateOne(u)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Users entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (u *Users) Unwrap() *Users {
|
||||
tx, ok := u.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Users is not a transactional entity")
|
||||
}
|
||||
u.config.driver = tx.drv
|
||||
return u
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (u *Users) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Users(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v", u.ID))
|
||||
builder.WriteString(", user=")
|
||||
builder.WriteString(u.User)
|
||||
builder.WriteString(", chara=")
|
||||
builder.WriteString(u.Chara)
|
||||
builder.WriteString(", skill=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Skill))
|
||||
builder.WriteString(", hp=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Hp))
|
||||
builder.WriteString(", attack=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Attack))
|
||||
builder.WriteString(", defense=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Defense))
|
||||
builder.WriteString(", critical=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Critical))
|
||||
builder.WriteString(", battle=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Battle))
|
||||
builder.WriteString(", win=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Win))
|
||||
builder.WriteString(", day=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Day))
|
||||
builder.WriteString(", percentage=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Percentage))
|
||||
builder.WriteString(", limit=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Limit))
|
||||
builder.WriteString(", status=")
|
||||
builder.WriteString(u.Status)
|
||||
builder.WriteString(", comment=")
|
||||
builder.WriteString(u.Comment)
|
||||
builder.WriteString(", created_at=")
|
||||
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", next=")
|
||||
builder.WriteString(u.Next)
|
||||
builder.WriteString(", updated_at=")
|
||||
builder.WriteString(u.UpdatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", url=")
|
||||
builder.WriteString(u.URL)
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// UsersSlice is a parsable slice of Users.
|
||||
type UsersSlice []*Users
|
||||
|
||||
func (u UsersSlice) config(cfg config) {
|
||||
for _i := range u {
|
||||
u[_i].config = cfg
|
||||
}
|
||||
}
|
124
ent/users/users.go
Normal file
124
ent/users/users.go
Normal file
@ -0,0 +1,124 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package users
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the users type in the database.
|
||||
Label = "users"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldUser holds the string denoting the user field in the database.
|
||||
FieldUser = "user"
|
||||
// FieldChara holds the string denoting the chara field in the database.
|
||||
FieldChara = "chara"
|
||||
// FieldSkill holds the string denoting the skill field in the database.
|
||||
FieldSkill = "skill"
|
||||
// FieldHp holds the string denoting the hp field in the database.
|
||||
FieldHp = "hp"
|
||||
// FieldAttack holds the string denoting the attack field in the database.
|
||||
FieldAttack = "attack"
|
||||
// FieldDefense holds the string denoting the defense field in the database.
|
||||
FieldDefense = "defense"
|
||||
// FieldCritical holds the string denoting the critical field in the database.
|
||||
FieldCritical = "critical"
|
||||
// FieldBattle holds the string denoting the battle field in the database.
|
||||
FieldBattle = "battle"
|
||||
// FieldWin holds the string denoting the win field in the database.
|
||||
FieldWin = "win"
|
||||
// FieldDay holds the string denoting the day field in the database.
|
||||
FieldDay = "day"
|
||||
// FieldPercentage holds the string denoting the percentage field in the database.
|
||||
FieldPercentage = "percentage"
|
||||
// FieldLimit holds the string denoting the limit field in the database.
|
||||
FieldLimit = "limit"
|
||||
// FieldStatus holds the string denoting the status field in the database.
|
||||
FieldStatus = "status"
|
||||
// FieldComment holds the string denoting the comment field in the database.
|
||||
FieldComment = "comment"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// FieldNext holds the string denoting the next field in the database.
|
||||
FieldNext = "next"
|
||||
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
|
||||
FieldUpdatedAt = "updated_at"
|
||||
// FieldURL holds the string denoting the url field in the database.
|
||||
FieldURL = "url"
|
||||
// Table holds the table name of the users in the database.
|
||||
Table = "users"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for users fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldUser,
|
||||
FieldChara,
|
||||
FieldSkill,
|
||||
FieldHp,
|
||||
FieldAttack,
|
||||
FieldDefense,
|
||||
FieldCritical,
|
||||
FieldBattle,
|
||||
FieldWin,
|
||||
FieldDay,
|
||||
FieldPercentage,
|
||||
FieldLimit,
|
||||
FieldStatus,
|
||||
FieldComment,
|
||||
FieldCreatedAt,
|
||||
FieldNext,
|
||||
FieldUpdatedAt,
|
||||
FieldURL,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// UserValidator is a validator for the "user" field. It is called by the builders before save.
|
||||
UserValidator func(string) error
|
||||
// DefaultChara holds the default value on creation for the "chara" field.
|
||||
DefaultChara string
|
||||
// DefaultSkill holds the default value on creation for the "skill" field.
|
||||
DefaultSkill int
|
||||
// DefaultHp holds the default value on creation for the "hp" field.
|
||||
DefaultHp int
|
||||
// DefaultAttack holds the default value on creation for the "attack" field.
|
||||
DefaultAttack int
|
||||
// DefaultDefense holds the default value on creation for the "defense" field.
|
||||
DefaultDefense int
|
||||
// DefaultCritical holds the default value on creation for the "critical" field.
|
||||
DefaultCritical int
|
||||
// DefaultBattle holds the default value on creation for the "battle" field.
|
||||
DefaultBattle int
|
||||
// DefaultWin holds the default value on creation for the "win" field.
|
||||
DefaultWin int
|
||||
// DefaultDay holds the default value on creation for the "day" field.
|
||||
DefaultDay int
|
||||
// DefaultPercentage holds the default value on creation for the "percentage" field.
|
||||
DefaultPercentage float64
|
||||
// DefaultLimit holds the default value on creation for the "limit" field.
|
||||
DefaultLimit bool
|
||||
// DefaultStatus holds the default value on creation for the "status" field.
|
||||
DefaultStatus string
|
||||
// DefaultComment holds the default value on creation for the "comment" field.
|
||||
DefaultComment string
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
// DefaultNext holds the default value on creation for the "next" field.
|
||||
DefaultNext string
|
||||
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
|
||||
DefaultUpdatedAt func() time.Time
|
||||
// DefaultURL holds the default value on creation for the "url" field.
|
||||
DefaultURL string
|
||||
)
|
2005
ent/users/where.go
Normal file
2005
ent/users/where.go
Normal file
File diff suppressed because it is too large
Load Diff
674
ent/users_create.go
Normal file
674
ent/users_create.go
Normal file
@ -0,0 +1,674 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"t/ent/users"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// UsersCreate is the builder for creating a Users entity.
|
||||
type UsersCreate struct {
|
||||
config
|
||||
mutation *UsersMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetUser sets the "user" field.
|
||||
func (uc *UsersCreate) SetUser(s string) *UsersCreate {
|
||||
uc.mutation.SetUser(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetChara sets the "chara" field.
|
||||
func (uc *UsersCreate) SetChara(s string) *UsersCreate {
|
||||
uc.mutation.SetChara(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableChara sets the "chara" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableChara(s *string) *UsersCreate {
|
||||
if s != nil {
|
||||
uc.SetChara(*s)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetSkill sets the "skill" field.
|
||||
func (uc *UsersCreate) SetSkill(i int) *UsersCreate {
|
||||
uc.mutation.SetSkill(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableSkill sets the "skill" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableSkill(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetSkill(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetHp sets the "hp" field.
|
||||
func (uc *UsersCreate) SetHp(i int) *UsersCreate {
|
||||
uc.mutation.SetHp(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableHp sets the "hp" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableHp(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetHp(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetAttack sets the "attack" field.
|
||||
func (uc *UsersCreate) SetAttack(i int) *UsersCreate {
|
||||
uc.mutation.SetAttack(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableAttack sets the "attack" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableAttack(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetAttack(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetDefense sets the "defense" field.
|
||||
func (uc *UsersCreate) SetDefense(i int) *UsersCreate {
|
||||
uc.mutation.SetDefense(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableDefense sets the "defense" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableDefense(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetDefense(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetCritical sets the "critical" field.
|
||||
func (uc *UsersCreate) SetCritical(i int) *UsersCreate {
|
||||
uc.mutation.SetCritical(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableCritical sets the "critical" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableCritical(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetCritical(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetBattle sets the "battle" field.
|
||||
func (uc *UsersCreate) SetBattle(i int) *UsersCreate {
|
||||
uc.mutation.SetBattle(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableBattle sets the "battle" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableBattle(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetBattle(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetWin sets the "win" field.
|
||||
func (uc *UsersCreate) SetWin(i int) *UsersCreate {
|
||||
uc.mutation.SetWin(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableWin sets the "win" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableWin(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetWin(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetDay sets the "day" field.
|
||||
func (uc *UsersCreate) SetDay(i int) *UsersCreate {
|
||||
uc.mutation.SetDay(i)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableDay sets the "day" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableDay(i *int) *UsersCreate {
|
||||
if i != nil {
|
||||
uc.SetDay(*i)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetPercentage sets the "percentage" field.
|
||||
func (uc *UsersCreate) SetPercentage(f float64) *UsersCreate {
|
||||
uc.mutation.SetPercentage(f)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillablePercentage sets the "percentage" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillablePercentage(f *float64) *UsersCreate {
|
||||
if f != nil {
|
||||
uc.SetPercentage(*f)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetLimit sets the "limit" field.
|
||||
func (uc *UsersCreate) SetLimit(b bool) *UsersCreate {
|
||||
uc.mutation.SetLimit(b)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableLimit sets the "limit" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableLimit(b *bool) *UsersCreate {
|
||||
if b != nil {
|
||||
uc.SetLimit(*b)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (uc *UsersCreate) SetStatus(s string) *UsersCreate {
|
||||
uc.mutation.SetStatus(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableStatus sets the "status" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableStatus(s *string) *UsersCreate {
|
||||
if s != nil {
|
||||
uc.SetStatus(*s)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetComment sets the "comment" field.
|
||||
func (uc *UsersCreate) SetComment(s string) *UsersCreate {
|
||||
uc.mutation.SetComment(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableComment sets the "comment" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableComment(s *string) *UsersCreate {
|
||||
if s != nil {
|
||||
uc.SetComment(*s)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (uc *UsersCreate) SetCreatedAt(t time.Time) *UsersCreate {
|
||||
uc.mutation.SetCreatedAt(t)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableCreatedAt(t *time.Time) *UsersCreate {
|
||||
if t != nil {
|
||||
uc.SetCreatedAt(*t)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNext sets the "next" field.
|
||||
func (uc *UsersCreate) SetNext(s string) *UsersCreate {
|
||||
uc.mutation.SetNext(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableNext sets the "next" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableNext(s *string) *UsersCreate {
|
||||
if s != nil {
|
||||
uc.SetNext(*s)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (uc *UsersCreate) SetUpdatedAt(t time.Time) *UsersCreate {
|
||||
uc.mutation.SetUpdatedAt(t)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableUpdatedAt(t *time.Time) *UsersCreate {
|
||||
if t != nil {
|
||||
uc.SetUpdatedAt(*t)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetURL sets the "url" field.
|
||||
func (uc *UsersCreate) SetURL(s string) *UsersCreate {
|
||||
uc.mutation.SetURL(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableURL sets the "url" field if the given value is not nil.
|
||||
func (uc *UsersCreate) SetNillableURL(s *string) *UsersCreate {
|
||||
if s != nil {
|
||||
uc.SetURL(*s)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// Mutation returns the UsersMutation object of the builder.
|
||||
func (uc *UsersCreate) Mutation() *UsersMutation {
|
||||
return uc.mutation
|
||||
}
|
||||
|
||||
// Save creates the Users in the database.
|
||||
func (uc *UsersCreate) Save(ctx context.Context) (*Users, error) {
|
||||
var (
|
||||
err error
|
||||
node *Users
|
||||
)
|
||||
uc.defaults()
|
||||
if len(uc.hooks) == 0 {
|
||||
if err = uc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = uc.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*UsersMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = uc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uc.mutation = mutation
|
||||
if node, err = uc.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(uc.hooks) - 1; i >= 0; i-- {
|
||||
if uc.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = uc.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, uc.mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (uc *UsersCreate) SaveX(ctx context.Context) *Users {
|
||||
v, err := uc.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (uc *UsersCreate) Exec(ctx context.Context) error {
|
||||
_, err := uc.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (uc *UsersCreate) ExecX(ctx context.Context) {
|
||||
if err := uc.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (uc *UsersCreate) defaults() {
|
||||
if _, ok := uc.mutation.Chara(); !ok {
|
||||
v := users.DefaultChara
|
||||
uc.mutation.SetChara(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Skill(); !ok {
|
||||
v := users.DefaultSkill
|
||||
uc.mutation.SetSkill(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Hp(); !ok {
|
||||
v := users.DefaultHp
|
||||
uc.mutation.SetHp(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Attack(); !ok {
|
||||
v := users.DefaultAttack
|
||||
uc.mutation.SetAttack(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Defense(); !ok {
|
||||
v := users.DefaultDefense
|
||||
uc.mutation.SetDefense(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Critical(); !ok {
|
||||
v := users.DefaultCritical
|
||||
uc.mutation.SetCritical(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Battle(); !ok {
|
||||
v := users.DefaultBattle
|
||||
uc.mutation.SetBattle(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Win(); !ok {
|
||||
v := users.DefaultWin
|
||||
uc.mutation.SetWin(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Day(); !ok {
|
||||
v := users.DefaultDay
|
||||
uc.mutation.SetDay(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Percentage(); !ok {
|
||||
v := users.DefaultPercentage
|
||||
uc.mutation.SetPercentage(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Limit(); !ok {
|
||||
v := users.DefaultLimit
|
||||
uc.mutation.SetLimit(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Status(); !ok {
|
||||
v := users.DefaultStatus
|
||||
uc.mutation.SetStatus(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Comment(); !ok {
|
||||
v := users.DefaultComment
|
||||
uc.mutation.SetComment(v)
|
||||
}
|
||||
if _, ok := uc.mutation.CreatedAt(); !ok {
|
||||
v := users.DefaultCreatedAt()
|
||||
uc.mutation.SetCreatedAt(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Next(); !ok {
|
||||
v := users.DefaultNext
|
||||
uc.mutation.SetNext(v)
|
||||
}
|
||||
if _, ok := uc.mutation.UpdatedAt(); !ok {
|
||||
v := users.DefaultUpdatedAt()
|
||||
uc.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
if _, ok := uc.mutation.URL(); !ok {
|
||||
v := users.DefaultURL
|
||||
uc.mutation.SetURL(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (uc *UsersCreate) check() error {
|
||||
if _, ok := uc.mutation.User(); !ok {
|
||||
return &ValidationError{Name: "user", err: errors.New(`ent: missing required field "Users.user"`)}
|
||||
}
|
||||
if v, ok := uc.mutation.User(); ok {
|
||||
if err := users.UserValidator(v); err != nil {
|
||||
return &ValidationError{Name: "user", err: fmt.Errorf(`ent: validator failed for field "Users.user": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uc *UsersCreate) sqlSave(ctx context.Context) (*Users, error) {
|
||||
_node, _spec := uc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{err.Error(), err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (uc *UsersCreate) createSpec() (*Users, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &Users{config: uc.config}
|
||||
_spec = &sqlgraph.CreateSpec{
|
||||
Table: users.Table,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: users.FieldID,
|
||||
},
|
||||
}
|
||||
)
|
||||
if value, ok := uc.mutation.User(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: users.FieldUser,
|
||||
})
|
||||
_node.User = value
|
||||
}
|
||||
if value, ok := uc.mutation.Chara(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: users.FieldChara,
|
||||
})
|
||||
_node.Chara = value
|
||||
}
|
||||
if value, ok := uc.mutation.Skill(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldSkill,
|
||||
})
|
||||
_node.Skill = value
|
||||
}
|
||||
if value, ok := uc.mutation.Hp(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldHp,
|
||||
})
|
||||
_node.Hp = value
|
||||
}
|
||||
if value, ok := uc.mutation.Attack(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldAttack,
|
||||
})
|
||||
_node.Attack = value
|
||||
}
|
||||
if value, ok := uc.mutation.Defense(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldDefense,
|
||||
})
|
||||
_node.Defense = value
|
||||
}
|
||||
if value, ok := uc.mutation.Critical(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldCritical,
|
||||
})
|
||||
_node.Critical = value
|
||||
}
|
||||
if value, ok := uc.mutation.Battle(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldBattle,
|
||||
})
|
||||
_node.Battle = value
|
||||
}
|
||||
if value, ok := uc.mutation.Win(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldWin,
|
||||
})
|
||||
_node.Win = value
|
||||
}
|
||||
if value, ok := uc.mutation.Day(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: users.FieldDay,
|
||||
})
|
||||
_node.Day = value
|
||||
}
|
||||
if value, ok := uc.mutation.Percentage(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeFloat64,
|
||||
Value: value,
|
||||
Column: users.FieldPercentage,
|
||||
})
|
||||
_node.Percentage = value
|
||||
}
|
||||
if value, ok := uc.mutation.Limit(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBool,
|
||||
Value: value,
|
||||
Column: users.FieldLimit,
|
||||
})
|
||||
_node.Limit = value
|
||||
}
|
||||
if value, ok := uc.mutation.Status(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: users.FieldStatus,
|
||||
})
|
||||
_node.Status = value
|
||||
}
|
||||
if value, ok := uc.mutation.Comment(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: users.FieldComment,
|
||||
})
|
||||
_node.Comment = value
|
||||
}
|
||||
if value, ok := uc.mutation.CreatedAt(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: users.FieldCreatedAt,
|
||||
})
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := uc.mutation.Next(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: users.FieldNext,
|
||||
})
|
||||
_node.Next = value
|
||||
}
|
||||
if value, ok := uc.mutation.UpdatedAt(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: users.FieldUpdatedAt,
|
||||
})
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := uc.mutation.URL(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: users.FieldURL,
|
||||
})
|
||||
_node.URL = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// UsersCreateBulk is the builder for creating many Users entities in bulk.
|
||||
type UsersCreateBulk struct {
|
||||
config
|
||||
builders []*UsersCreate
|
||||
}
|
||||
|
||||
// Save creates the Users entities in the database.
|
||||
func (ucb *UsersCreateBulk) Save(ctx context.Context) ([]*Users, error) {
|
||||
specs := make([]*sqlgraph.CreateSpec, len(ucb.builders))
|
||||
nodes := make([]*Users, len(ucb.builders))
|
||||
mutators := make([]Mutator, len(ucb.builders))
|
||||
for i := range ucb.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := ucb.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*UsersMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
var err error
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, ucb.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, ucb.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{err.Error(), err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
mutation.done = true
|
||||
if specs[i].ID.Value != nil {
|
||||
id := specs[i].ID.Value.(int64)
|
||||
nodes[i].ID = int(id)
|
||||
}
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, ucb.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (ucb *UsersCreateBulk) SaveX(ctx context.Context) []*Users {
|
||||
v, err := ucb.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (ucb *UsersCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := ucb.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ucb *UsersCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := ucb.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
111
ent/users_delete.go
Normal file
111
ent/users_delete.go
Normal file
@ -0,0 +1,111 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"t/ent/predicate"
|
||||
"t/ent/users"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// UsersDelete is the builder for deleting a Users entity.
|
||||
type UsersDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *UsersMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UsersDelete builder.
|
||||
func (ud *UsersDelete) Where(ps ...predicate.Users) *UsersDelete {
|
||||
ud.mutation.Where(ps...)
|
||||
return ud
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (ud *UsersDelete) Exec(ctx context.Context) (int, error) {
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
if len(ud.hooks) == 0 {
|
||||
affected, err = ud.sqlExec(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*UsersMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
ud.mutation = mutation
|
||||
affected, err = ud.sqlExec(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(ud.hooks) - 1; i >= 0; i-- {
|
||||
if ud.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = ud.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, ud.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ud *UsersDelete) ExecX(ctx context.Context) int {
|
||||
n, err := ud.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (ud *UsersDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := &sqlgraph.DeleteSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: users.Table,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: users.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
if ps := ud.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return sqlgraph.DeleteNodes(ctx, ud.driver, _spec)
|
||||
}
|
||||
|
||||
// UsersDeleteOne is the builder for deleting a single Users entity.
|
||||
type UsersDeleteOne struct {
|
||||
ud *UsersDelete
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (udo *UsersDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := udo.ud.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{users.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (udo *UsersDeleteOne) ExecX(ctx context.Context) {
|
||||
udo.ud.ExecX(ctx)
|
||||
}
|
920
ent/users_query.go
Normal file
920
ent/users_query.go
Normal file
@ -0,0 +1,920 @@
|
||||
// Code generated by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"t/ent/predicate"
|
||||
"t/ent/users"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// UsersQuery is the builder for querying Users entities.
|
||||
type UsersQuery struct {
|
||||
config
|
||||
limit *int
|
||||
offset *int
|
||||
unique *bool
|
||||
order []OrderFunc
|
||||
fields []string
|
||||
predicates []predicate.Users
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the UsersQuery builder.
|
||||
func (uq *UsersQuery) Where(ps ...predicate.Users) *UsersQuery {
|
||||
uq.predicates = append(uq.predicates, ps...)
|
||||
return uq
|
||||
}
|
||||
|
||||
// Limit adds a limit step to the query.
|
||||
func (uq *UsersQuery) Limit(limit int) *UsersQuery {
|
||||
uq.limit = &limit
|
||||
return uq
|
||||
}
|
||||
|
||||
// Offset adds an offset step to the query.
|
||||
func (uq *UsersQuery) Offset(offset int) *UsersQuery {
|
||||
uq.offset = &offset
|
||||
return uq
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (uq *UsersQuery) Unique(unique bool) *UsersQuery {
|
||||
uq.unique = &unique
|
||||
return uq
|
||||
}
|
||||
|
||||
// Order adds an order step to the query.
|
||||
func (uq *UsersQuery) Order(o ...OrderFunc) *UsersQuery {
|
||||
uq.order = append(uq.order, o...)
|
||||
return uq
|
||||
}
|
||||
|
||||
// First returns the first Users entity from the query.
|
||||
// Returns a *NotFoundError when no Users was found.
|
||||
func (uq *UsersQuery) First(ctx context.Context) (*Users, error) {
|
||||
nodes, err := uq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{users.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (uq *UsersQuery) FirstX(ctx context.Context) *Users {
|
||||
node, err := uq.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first Users ID from the query.
|
||||
// Returns a *NotFoundError when no Users ID was found.
|
||||
func (uq *UsersQuery) FirstID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = uq.Limit(1).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{users.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (uq *UsersQuery) FirstIDX(ctx context.Context) int {
|
||||
id, err := uq.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single Users entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when exactly one Users entity is not found.
|
||||
// Returns a *NotFoundError when no Users entities are found.
|
||||
func (uq *UsersQuery) Only(ctx context.Context) (*Users, error) {
|
||||
nodes, err := uq.Limit(2).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{users.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{users.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (uq *UsersQuery) OnlyX(ctx context.Context) *Users {
|
||||
node, err := uq.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only Users ID in the query.
|
||||
// Returns a *NotSingularError when exactly one Users ID is not found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (uq *UsersQuery) OnlyID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = uq.Limit(2).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = &NotSingularError{users.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (uq *UsersQuery) OnlyIDX(ctx context.Context) int {
|
||||
id, err := uq.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of UsersSlice.
|
||||
func (uq *UsersQuery) All(ctx context.Context) ([]*Users, error) {
|
||||
if err := uq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return uq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (uq *UsersQuery) AllX(ctx context.Context) []*Users {
|
||||
nodes, err := uq.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Users IDs.
|
||||
func (uq *UsersQuery) IDs(ctx context.Context) ([]int, error) {
|
||||
var ids []int
|
||||
if err := uq.Select(users.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (uq *UsersQuery) IDsX(ctx context.Context) []int {
|
||||
ids, err := uq.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (uq *UsersQuery) Count(ctx context.Context) (int, error) {
|
||||
if err := uq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (uq *UsersQuery) CountX(ctx context.Context) int {
|
||||
count, err := uq.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (uq *UsersQuery) Exist(ctx context.Context) (bool, error) {
|
||||
if err := uq.prepareQuery(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return uq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (uq *UsersQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := uq.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the UsersQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (uq *UsersQuery) Clone() *UsersQuery {
|
||||
if uq == nil {
|
||||
return nil
|
||||
}
|
||||
return &UsersQuery{
|
||||
config: uq.config,
|
||||
limit: uq.limit,
|
||||
offset: uq.offset,
|
||||
order: append([]OrderFunc{}, uq.order...),
|
||||
predicates: append([]predicate.Users{}, uq.predicates...),
|
||||
// clone intermediate query.
|
||||
sql: uq.sql.Clone(),
|
||||
path: uq.path,
|
||||
}
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// User string `json:"user,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Users.Query().
|
||||
// GroupBy(users.FieldUser).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func (uq *UsersQuery) GroupBy(field string, fields ...string) *UsersGroupBy {
|
||||
group := &UsersGroupBy{config: uq.config}
|
||||
group.fields = append([]string{field}, fields...)
|
||||
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
|
||||
if err := uq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return uq.sqlQuery(ctx), nil
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
// Select allows the selection one or more fields/columns for the given query,
|
||||
// instead of selecting all fields in the entity.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// User string `json:"user,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Users.Query().
|
||||
// Select(users.FieldUser).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func (uq *UsersQuery) Select(fields ...string) *UsersSelect {
|
||||
uq.fields = append(uq.fields, fields...)
|
||||
return &UsersSelect{UsersQuery: uq}
|
||||
}
|
||||
|
||||
func (uq *UsersQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, f := range uq.fields {
|
||||
if !users.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if uq.path != nil {
|
||||
prev, err := uq.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
uq.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uq *UsersQuery) sqlAll(ctx context.Context) ([]*Users, error) {
|
||||
var (
|
||||
nodes = []*Users{}
|
||||
_spec = uq.querySpec()
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
|
||||
node := &Users{config: uq.config}
|
||||
nodes = append(nodes, node)
|
||||
return node.scanValues(columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []interface{}) error {
|
||||
if len(nodes) == 0 {
|
||||
return fmt.Errorf("ent: Assign called without calling ScanValues")
|
||||
}
|
||||
node := nodes[len(nodes)-1]
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (uq *UsersQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := uq.querySpec()
|
||||
_spec.Node.Columns = uq.fields
|
||||
if len(uq.fields) > 0 {
|
||||
_spec.Unique = uq.unique != nil && *uq.unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, uq.driver, _spec)
|
||||
}
|
||||
|
||||
func (uq *UsersQuery) sqlExist(ctx context.Context) (bool, error) {
|
||||
n, err := uq.sqlCount(ctx)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
}
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
func (uq *UsersQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := &sqlgraph.QuerySpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: users.Table,
|
||||
Columns: users.Columns,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: users.FieldID,
|
||||
},
|
||||
},
|
||||
From: uq.sql,
|
||||
Unique: true,
|
||||
}
|
||||
if unique := uq.unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
}
|
||||
if fields := uq.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, users.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != users.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := uq.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := uq.limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := uq.offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := uq.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (uq *UsersQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(uq.driver.Dialect())
|
||||
t1 := builder.Table(users.Table)
|
||||
columns := uq.fields
|
||||
if len(columns) == 0 {
|
||||
columns = users.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if uq.sql != nil {
|
||||
selector = uq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if uq.unique != nil && *uq.unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range uq.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range uq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := uq.offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := uq.limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// UsersGroupBy is the group-by builder for Users entities.
|
||||
type UsersGroupBy struct {
|
||||
config
|
||||
fields []string
|
||||
fns []AggregateFunc
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (ugb *UsersGroupBy) Aggregate(fns ...AggregateFunc) *UsersGroupBy {
|
||||
ugb.fns = append(ugb.fns, fns...)
|
||||
return ugb
|
||||
}
|
||||
|
||||
// Scan applies the group-by query and scans the result into the given value.
|
||||
func (ugb *UsersGroupBy) Scan(ctx context.Context, v interface{}) error {
|
||||
query, err := ugb.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ugb.sql = query
|
||||
return ugb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) ScanX(ctx context.Context, v interface{}) {
|
||||
if err := ugb.Scan(ctx, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns list of strings from group-by.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(ugb.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersGroupBy.Strings is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := ugb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) StringsX(ctx context.Context) []string {
|
||||
v, err := ugb.Strings(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// String returns a single string from a group-by query.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) String(ctx context.Context) (_ string, err error) {
|
||||
var v []string
|
||||
if v, err = ugb.Strings(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersGroupBy.Strings returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// StringX is like String, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) StringX(ctx context.Context) string {
|
||||
v, err := ugb.String(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints returns list of ints from group-by.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(ugb.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersGroupBy.Ints is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := ugb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) IntsX(ctx context.Context) []int {
|
||||
v, err := ugb.Ints(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Int returns a single int from a group-by query.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) Int(ctx context.Context) (_ int, err error) {
|
||||
var v []int
|
||||
if v, err = ugb.Ints(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersGroupBy.Ints returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// IntX is like Int, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) IntX(ctx context.Context) int {
|
||||
v, err := ugb.Int(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64s returns list of float64s from group-by.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(ugb.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersGroupBy.Float64s is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := ugb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := ugb.Float64s(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64 returns a single float64 from a group-by query.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) Float64(ctx context.Context) (_ float64, err error) {
|
||||
var v []float64
|
||||
if v, err = ugb.Float64s(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersGroupBy.Float64s returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Float64X is like Float64, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) Float64X(ctx context.Context) float64 {
|
||||
v, err := ugb.Float64(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bools returns list of bools from group-by.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(ugb.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersGroupBy.Bools is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := ugb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) BoolsX(ctx context.Context) []bool {
|
||||
v, err := ugb.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bool returns a single bool from a group-by query.
|
||||
// It is only allowed when executing a group-by query with one field.
|
||||
func (ugb *UsersGroupBy) Bool(ctx context.Context) (_ bool, err error) {
|
||||
var v []bool
|
||||
if v, err = ugb.Bools(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersGroupBy.Bools returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// BoolX is like Bool, but panics if an error occurs.
|
||||
func (ugb *UsersGroupBy) BoolX(ctx context.Context) bool {
|
||||
v, err := ugb.Bool(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (ugb *UsersGroupBy) sqlScan(ctx context.Context, v interface{}) error {
|
||||
for _, f := range ugb.fields {
|
||||
if !users.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
|
||||
}
|
||||
}
|
||||
selector := ugb.sqlQuery()
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := ugb.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (ugb *UsersGroupBy) sqlQuery() *sql.Selector {
|
||||
selector := ugb.sql.Select()
|
||||
aggregation := make([]string, 0, len(ugb.fns))
|
||||
for _, fn := range ugb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
// If no columns were selected in a custom aggregation function, the default
|
||||
// selection is the fields used for "group-by", and the aggregation functions.
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(ugb.fields)+len(ugb.fns))
|
||||
for _, f := range ugb.fields {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
return selector.GroupBy(selector.Columns(ugb.fields...)...)
|
||||
}
|
||||
|
||||
// UsersSelect is the builder for selecting fields of Users entities.
|
||||
type UsersSelect struct {
|
||||
*UsersQuery
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (us *UsersSelect) Scan(ctx context.Context, v interface{}) error {
|
||||
if err := us.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
us.sql = us.UsersQuery.sqlQuery(ctx)
|
||||
return us.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (us *UsersSelect) ScanX(ctx context.Context, v interface{}) {
|
||||
if err := us.Scan(ctx, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersSelect.Strings is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (us *UsersSelect) StringsX(ctx context.Context) []string {
|
||||
v, err := us.Strings(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// String returns a single string from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) String(ctx context.Context) (_ string, err error) {
|
||||
var v []string
|
||||
if v, err = us.Strings(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersSelect.Strings returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// StringX is like String, but panics if an error occurs.
|
||||
func (us *UsersSelect) StringX(ctx context.Context) string {
|
||||
v, err := us.String(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersSelect.Ints is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (us *UsersSelect) IntsX(ctx context.Context) []int {
|
||||
v, err := us.Ints(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Int returns a single int from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) Int(ctx context.Context) (_ int, err error) {
|
||||
var v []int
|
||||
if v, err = us.Ints(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersSelect.Ints returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// IntX is like Int, but panics if an error occurs.
|
||||
func (us *UsersSelect) IntX(ctx context.Context) int {
|
||||
v, err := us.Int(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersSelect.Float64s is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (us *UsersSelect) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := us.Float64s(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) Float64(ctx context.Context) (_ float64, err error) {
|
||||
var v []float64
|
||||
if v, err = us.Float64s(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersSelect.Float64s returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Float64X is like Float64, but panics if an error occurs.
|
||||
func (us *UsersSelect) Float64X(ctx context.Context) float64 {
|
||||
v, err := us.Float64(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UsersSelect.Bools is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (us *UsersSelect) BoolsX(ctx context.Context) []bool {
|
||||
v, err := us.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
|
||||
func (us *UsersSelect) Bool(ctx context.Context) (_ bool, err error) {
|
||||
var v []bool
|
||||
if v, err = us.Bools(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{users.Label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: UsersSelect.Bools returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// BoolX is like Bool, but panics if an error occurs.
|
||||
func (us *UsersSelect) BoolX(ctx context.Context) bool {
|
||||
v, err := us.Bool(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (us *UsersSelect) sqlScan(ctx context.Context, v interface{}) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := us.sql.Query()
|
||||
if err := us.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
1316
ent/users_update.go
Normal file
1316
ent/users_update.go
Normal file
File diff suppressed because it is too large
Load Diff
29
fly.toml
Normal file
29
fly.toml
Normal file
@ -0,0 +1,29 @@
|
||||
# fly.toml file generated for ent on 2022-08-31T13:39:30+09:00
|
||||
|
||||
app = "ent"
|
||||
kill_signal = "SIGINT"
|
||||
kill_timeout = 5
|
||||
|
||||
[build]
|
||||
builder = "paketobuildpacks/builder:base"
|
||||
buildpacks = ["gcr.io/paketo-buildpacks/go"]
|
||||
|
||||
[env]
|
||||
PORT = "8080"
|
||||
|
||||
[processes]
|
||||
api = "bin/t"
|
||||
|
||||
[[services]]
|
||||
internal_port = 8080
|
||||
processes = ["api"]
|
||||
protocol = "tcp"
|
||||
|
||||
[[services.ports]]
|
||||
force_https = true
|
||||
handlers = ["http"]
|
||||
port = 80
|
||||
|
||||
[[services.ports]]
|
||||
handlers = ["tls", "http"]
|
||||
port = 443
|
59
go.mod
Normal file
59
go.mod
Normal file
@ -0,0 +1,59 @@
|
||||
module t
|
||||
|
||||
// +heroku goVersion go1.17
|
||||
go 1.17
|
||||
|
||||
require (
|
||||
entgo.io/ent v0.10.0
|
||||
github.com/go-chi/chi/v5 v5.0.4
|
||||
github.com/jackc/pgx/v4 v4.15.0
|
||||
github.com/lib/pq v1.10.4
|
||||
github.com/mailru/easyjson v0.7.7
|
||||
go.uber.org/zap v1.21.0
|
||||
)
|
||||
|
||||
require (
|
||||
entgo.io/contrib v0.2.1-0.20220210075301-2b75bf138815 // indirect
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
|
||||
github.com/ariga/ogent v0.0.0-20220224071349-f1dbffa2e32a // indirect
|
||||
github.com/ghodss/yaml v1.0.0 // indirect
|
||||
github.com/go-logr/logr v1.2.2 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-openapi/inflect v0.19.0 // indirect
|
||||
github.com/golang/mock v1.6.0 // indirect
|
||||
github.com/google/go-cmp v0.5.7 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.11.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.10.0 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/kyokomi/lottery v1.2.0 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/uniplaces/carbon v0.1.6 // indirect
|
||||
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce // indirect
|
||||
golang.org/x/mod v0.5.1 // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
ariga.io/atlas v0.3.5 // indirect
|
||||
github.com/agext/levenshtein v1.2.3 // indirect
|
||||
github.com/go-faster/errors v0.5.0
|
||||
github.com/go-faster/jx v0.32.2
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/hashicorp/hcl/v2 v2.11.1 // indirect
|
||||
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
|
||||
github.com/ogen-go/ogen v0.19.0
|
||||
github.com/sergi/go-diff v1.1.0 // indirect
|
||||
github.com/zclconf/go-cty v1.10.0 // indirect
|
||||
go.opentelemetry.io/otel v1.4.1
|
||||
go.opentelemetry.io/otel/metric v0.27.0
|
||||
go.opentelemetry.io/otel/trace v1.4.1
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.7.0 // indirect
|
||||
golang.org/x/sys v0.0.0-20220222200937-f2425489ef4c // indirect
|
||||
)
|
146
main.go
Normal file
146
main.go
Normal file
@ -0,0 +1,146 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
"t/ent"
|
||||
"net/http"
|
||||
"math/rand"
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"database/sql"
|
||||
entsql "entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect"
|
||||
_ "github.com/jackc/pgx/v4/stdlib"
|
||||
_ "github.com/lib/pq"
|
||||
"t/ent/ogent"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"github.com/kyokomi/lottery"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
user string `json:"user"`
|
||||
created_at time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func Open(databaseUrl string) *ent.Client {
|
||||
db, err := sql.Open("pgx", databaseUrl)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
drv := entsql.OpenDB(dialect.Postgres, db)
|
||||
return ent.NewClient(ent.Driver(drv))
|
||||
}
|
||||
|
||||
func Random(i int) (l int){
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
l = rand.Intn(i)
|
||||
for l == 0 {
|
||||
l = rand.Intn(i)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Kira(i int) (l bool){
|
||||
lot := lottery.New(rand.New(rand.NewSource(time.Now().UnixNano())))
|
||||
if lot.Lot(i) {
|
||||
l = true
|
||||
} else {
|
||||
l = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type handler struct {
|
||||
*ogent.OgentHandler
|
||||
client *ent.Client
|
||||
}
|
||||
|
||||
|
||||
func (h handler) DrawStart(ctx context.Context, params ogent.DrawStartParams) (ogent.DrawStartNoContent, error) {
|
||||
return ogent.DrawStartNoContent{}, h.client.Users.UpdateOneID(params.ID).Exec(ctx)
|
||||
}
|
||||
|
||||
func (h handler) DrawDone(ctx context.Context, params ogent.DrawDoneParams) (ogent.DrawDoneNoContent, error) {
|
||||
body := h.client.Users.GetX(ctx, params.ID)
|
||||
total := body.Day
|
||||
total_n := total + 1
|
||||
jst, err := time.LoadLocation("Asia/Tokyo")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
t := time.Now().In(jst)
|
||||
tt := t.Format("20060102")
|
||||
f := body.UpdatedAt.Add(time.Hour * 24 * 1).In(jst)
|
||||
ff := f.Format("20060102")
|
||||
fff := body.Next
|
||||
if tt < fff {
|
||||
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetNext(ff).SetLimit(true).Exec(ctx)
|
||||
}
|
||||
|
||||
bb := h.client.Users.GetX(ctx, body.Battle)
|
||||
ba := bb.Attack
|
||||
aa := body.Attack
|
||||
attack_p := aa - ba
|
||||
win_n := body.Win + 1
|
||||
pat := float64(win_n) / float64(total_n) * 100
|
||||
var at int
|
||||
if attack_p > 0 {
|
||||
at = Random(55)
|
||||
} else {
|
||||
at = Random(45)
|
||||
}
|
||||
if at > 25 {
|
||||
b := Random(4)
|
||||
if b == 1 {
|
||||
b := Random(10)
|
||||
com := "attack+" + strconv.Itoa(b)
|
||||
a := body.Attack + b
|
||||
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetAttack(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetLimit(false).SetComment(com).Exec(ctx)
|
||||
} else if b == 2 {
|
||||
b := Random(10)
|
||||
com := "defense+" + strconv.Itoa(b)
|
||||
a := body.Defense + b
|
||||
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetDefense(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetLimit(false).SetComment(com).Exec(ctx)
|
||||
} else if b == 3 {
|
||||
b := Random(10)
|
||||
com := "hp+" + strconv.Itoa(b)
|
||||
a := body.Hp + b
|
||||
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetHp(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetComment(com).SetLimit(false).Exec(ctx)
|
||||
} else {
|
||||
b := Random(10)
|
||||
com := "critical+" + strconv.Itoa(b)
|
||||
a := body.Critical + b
|
||||
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetCritical(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetComment(com).SetLimit(false).SetWin(win_n).Exec(ctx)
|
||||
}
|
||||
} else {
|
||||
com := "loss"
|
||||
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetNext(ff).SetDay(total_n).SetComment(com).SetLimit(false).Exec(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
url := os.Getenv("DATABASE_URL") + "?sslmode=require"
|
||||
client, err := ent.Open("postgres", url)
|
||||
//client, err := Open(url)
|
||||
if err := client.Schema.Create(context.Background(), schema.WithAtlas(true)); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
port := os.Getenv("PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
h := handler{
|
||||
OgentHandler: ogent.NewOgentHandler(client),
|
||||
client: client,
|
||||
}
|
||||
srv,err := ogent.NewServer(h)
|
||||
//srv,err := ogent.NewServer(ogent.NewOgentHandler(client))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := http.ListenAndServe(":" + port, srv); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
78
readme.md
Normal file
78
readme.md
Normal file
@ -0,0 +1,78 @@
|
||||
heroku open-api ent example
|
||||
|
||||
- go-module-name : t
|
||||
|
||||
- onconflict
|
||||
|
||||
```sh
|
||||
$ curl -X POST -H "Content-Type: application/json" -d '{"user":"syui"}' api.syui.cf/users
|
||||
...ok
|
||||
|
||||
$ !!
|
||||
...err
|
||||
|
||||
$ heroku logs
|
||||
```
|
||||
|
||||
|
||||
```sh
|
||||
# delete
|
||||
$ curl -X DELETE https://api.syui.cf/users/1
|
||||
|
||||
# card draw
|
||||
$ curl -X PUT api.syui.cf/users/1/d
|
||||
$ curl api.syui.cf/users/1
|
||||
|
||||
# patch
|
||||
$ curl -X PATCH -H "Content-Type: application/json" -d '{"battle":2}' api.syui.cf/users/1
|
||||
$ curl -X PATCH -H "Content-Type: application/json" -d '{"limit":false}' api.syui.cf/users/1
|
||||
$ d=`date "+%Y%m%d"`
|
||||
$ curl -X PATCH -H "Content-Type: application/json" -d "{\"next\":\"$d\"}" api.syui.cf/users/1
|
||||
```
|
||||
|
||||
```sh
|
||||
$ vim ./ent/ogent/ogent.go
|
||||
// 新規登録の停止
|
||||
// CreateUsers handles POST /users-slice requests.
|
||||
func (h *OgentHandler) CreateUsers(ctx context.Context, req CreateUsersReq) (CreateUsersRes, error) {
|
||||
b := h.client.Users.Create()
|
||||
//b.SetUser(req.User)
|
||||
b.SetUser("syui")
|
||||
}
|
||||
|
||||
// 削除の無効
|
||||
// DeleteUsers handles DELETE /users-slice/{id} requests.
|
||||
func (h *OgentHandler) DeleteUsers(ctx context.Context, params DeleteUsersParams) (DeleteUsersRes, error) {
|
||||
if params.ID != 1 {
|
||||
err := h.client.Users.DeleteOneID(params.ID).Exec(ctx)
|
||||
}
|
||||
return new(DeleteUsersNoContent), nil
|
||||
}
|
||||
|
||||
// 要素の書き換えの禁止
|
||||
// UpdateUsers handles PATCH /users-slice/{id} requests.
|
||||
func (h *OgentHandler) UpdateUsers(ctx context.Context, req UpdateUsersReq, params UpdateUsersParams) (UpdateUsersRes, error) {
|
||||
b := h.client.Users.UpdateOneID(params.ID)
|
||||
// Add all fields.
|
||||
//if v, ok := req.Hp.Get(); ok {
|
||||
// b.SetHp(v)
|
||||
//}
|
||||
```
|
||||
|
||||
ref :
|
||||
|
||||
- https://github.com/ent/ent/blob/master/dialect/sql/schema/postgres_test.go
|
||||
|
||||
- https://github.com/go-kratos/beer-shop/tree/main/app/catalog/service/internal/data/ent
|
||||
|
||||
- https://entgo.io/ja/blog/2022/02/15/generate-rest-crud-with-ent-and-ogen/
|
||||
|
||||
- https://github.com/ariga/ogent/blob/main/example/todo/ent/entc.go
|
||||
|
||||
```sh
|
||||
$ vim ent/entc.go
|
||||
$ vim ent/schema/users.go
|
||||
$ go generate ./...
|
||||
$ go build
|
||||
$ ./t
|
||||
```
|
Loading…
x
Reference in New Issue
Block a user