mochi

package module
v0.0.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2024 License: MIT Imports: 18 Imported by: 14

Documentation

Index

Constants

View Source
const (
	AuthHeaderName = "Authorization"
)
View Source
const (
	QueryTimeout = time.Second
)
View Source
const (
	TokenExpirationTime = time.Hour * 24
)

Variables

View Source
var ErrNotFound = &ErrResponse{HTTPStatusCode: 404, StatusText: "Resource not found."}
View Source
var ErrRecordNotFound = errors.New("record not found")

Functions

func BuildAppOpts

func BuildAppOpts() []fx.Option

func BuildServerOpts

func BuildServerOpts() []fx.Option

func ErrInvalidRequest

func ErrInvalidRequest(err error) render.Renderer

func ErrRender

func ErrRender(err error) render.Renderer

func ErrUnauthorized

func ErrUnauthorized(err error) render.Renderer

func ErrUnknown

func ErrUnknown(err error) render.Renderer

func NewFxLogger

func NewFxLogger(logger LoggerService) fxevent.Logger

func NewRouter

func NewRouter() *chi.Mux

func NewServer

func NewServer(lc fx.Lifecycle, router *chi.Mux, logger LoggerService) *http.Server

Types

type AuthService

type AuthService interface {
	AuthRequired() func(http.Handler) http.Handler
	AdminRequired() func(http.Handler) http.Handler
	GetUserFromCtx(ctx context.Context) (User, error)
	LoginUser(ctx context.Context, username, password string) (string, error)
}

type AuthServiceParams

type AuthServiceParams struct {
	fx.In

	Logger      LoggerService
	UserService UserService
}

type AuthServiceResult

type AuthServiceResult struct {
	fx.Out

	AuthService AuthService
}

func NewAuthService

func NewAuthService(params AuthServiceParams) (AuthServiceResult, error)

type Claims added in v0.0.2

type Claims struct {
	Sub uint      `json:"sub"`
	Exp time.Time `json:"exp"`
	Iat time.Time `json:"iat"`
	Nbf time.Time `json:"nbf"`
	Aud string    `json:"aud"`
	Iss string    `json:"iss"`
}

func NewClaims added in v0.0.2

func NewClaims(user User, audience, issuer string) *Claims

func (*Claims) GetAudience added in v0.0.2

func (c *Claims) GetAudience() (jwt.ClaimStrings, error)

func (*Claims) GetExpirationTime added in v0.0.2

func (c *Claims) GetExpirationTime() (*jwt.NumericDate, error)

func (*Claims) GetIssuedAt added in v0.0.2

func (c *Claims) GetIssuedAt() (*jwt.NumericDate, error)

func (*Claims) GetIssuer added in v0.0.2

func (c *Claims) GetIssuer() (string, error)

func (*Claims) GetNotBefore added in v0.0.2

func (c *Claims) GetNotBefore() (*jwt.NumericDate, error)

func (*Claims) GetSubject added in v0.0.2

func (c *Claims) GetSubject() (string, error)

type Controller

type Controller[M Resource] interface {
	List(w http.ResponseWriter, r *http.Request)
	Create(w http.ResponseWriter, r *http.Request)
	Get(w http.ResponseWriter, r *http.Request)
	Update(w http.ResponseWriter, r *http.Request)
	Delete(w http.ResponseWriter, r *http.Request)

	ItemFromContext(ctx context.Context) (M, error)
	ItemContextMiddleware(next http.Handler) http.Handler
	UserAccessMiddleware(next http.Handler) http.Handler

	GetRouter() *chi.Mux
}

func NewController

func NewController[M Resource](
	svc Service[M],
	logger LoggerService,
	authSvc AuthService,
	createRequestConstructor ResourceRequestConstructor[M],
	updateRequestConstructor ResourceRequestConstructor[M],
	opts ...ControllerOption[M],
) Controller[M]

type ControllerOption

type ControllerOption[M Resource] func(*controller[M])

func WithContextKey

func WithContextKey[M Resource](key ResourceContextKey) ControllerOption[M]

func WithDetailRoute

func WithDetailRoute[M Resource](method, path string, handler http.HandlerFunc) ControllerOption[M]

func WithUserAccessFunc added in v0.0.5

func WithUserAccessFunc[M Resource](accessFunc UserResourceAccessFunc[M]) ControllerOption[M]

type DBService added in v0.0.3

type DBService interface {
	CreateOne(ctx context.Context, record interface{}) error
	UpdateOne(ctx context.Context, recordID uint, record interface{}) error
	DEPUpdateOne(ctx context.Context, record interface{}) error
	DeleteOne(ctx context.Context, recordID uint, record interface{}) error
	FindOne(
		ctx context.Context,
		result interface{},
		joins []string,
		preloads []string,
		query interface{},
		args ...interface{},
	) error
	FindMany(
		ctx context.Context,
		result interface{},
		joins []string,
		preloads []string,
		query interface{},
		args ...interface{},
	) error

	GetSession(ctx context.Context) (*gorm.DB, context.CancelFunc)
	Migrate(ctx context.Context) error
	DropAll(ctx context.Context) error
}

type DBServiceParams added in v0.0.3

type DBServiceParams struct {
	fx.In

	Models ModelList
}

type DbServiceResult added in v0.0.3

type DbServiceResult struct {
	fx.Out

	DBService DBService
}

func NewDBService added in v0.0.3

func NewDBService(params DBServiceParams) (DbServiceResult, error)

type ErrResponse

type ErrResponse struct {
	Err            error `json:"-"` // low-level runtime error
	HTTPStatusCode int   `json:"-"` // http response status code

	StatusText string `json:"status"`          // user-level status message
	AppCode    int64  `json:"code,omitempty"`  // application-specific error code
	ErrorText  string `json:"error,omitempty"` // application-level error message, for debugging
}

func (*ErrResponse) Render

func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error

type LoggerService

type LoggerService interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
	Logger() *slog.Logger
}

type LoggerServiceParams

type LoggerServiceParams struct {
	fx.In
}

type LoggerServiceResult

type LoggerServiceResult struct {
	fx.Out

	LoggerService LoggerService
}

func NewLoggerService

func NewLoggerService(params LoggerServiceParams) (LoggerServiceResult, error)

type Model added in v0.0.3

type Model interface {
	GetID() uint
}

type ModelList added in v0.0.8

type ModelList []interface{}

type Repository added in v0.0.3

type Repository[M Model] interface {
	FindOne(ctx context.Context, query string, args ...interface{}) (M, error)
	FindOneByID(ctx context.Context, itemID uint, query string, args ...interface{}) (M, error)
	FindOneByUser(ctx context.Context, userID uint, query string, args ...interface{}) (M, error)
	FindManyByUser(ctx context.Context, userID uint, query string, args ...interface{}) ([]M, error)
	CreateOne(ctx context.Context, item M) error
	UpdateOne(ctx context.Context, itemID uint, item M) error
	DeleteOne(ctx context.Context, itemID uint) error
}

func NewRepository added in v0.0.4

func NewRepository[M Model](
	db DBService,
	logger LoggerService,
	opts ...RepositoryOption[M],
) Repository[M]

type RepositoryOption added in v0.0.4

type RepositoryOption[M Model] func(*repository[M])

func WithJoinTables added in v0.0.3

func WithJoinTables[M Model](joinTables ...string) RepositoryOption[M]

func WithPreloadTables added in v0.0.3

func WithPreloadTables[M Model](preloadTables ...string) RepositoryOption[M]

func WithTableName added in v0.0.3

func WithTableName[M Model](tableName string) RepositoryOption[M]

type Resource added in v0.0.3

type Resource interface {
	Model
	ToDTO() render.Renderer
}

type ResourceContextKey

type ResourceContextKey int

type ResourceRequestConstructor

type ResourceRequestConstructor[M Resource] func(*http.Request, User) (M, error)

type Route

type Route struct {
	Method  string
	Path    string
	Handler http.HandlerFunc
}

type Service added in v0.0.3

type Service[M Resource] interface {
	ListByUser(ctx context.Context, userID uint) ([]M, error)
	CreateOne(ctx context.Context, userID uint, item M) (M, error)
	GetOne(ctx context.Context, itemID uint) (M, error)
	UpdateOne(ctx context.Context, itemID uint, item M) (M, error)
	DeleteOne(ctx context.Context, itemID uint) error
}

func NewService added in v0.0.3

func NewService[M Resource](
	repo Repository[M],
	opts ...ServiceOption[M],
) Service[M]

type ServiceOption added in v0.0.3

type ServiceOption[M Resource] func(*service[M])

func WithGetQuery added in v0.0.3

func WithGetQuery[M Resource](query string, args ...interface{}) ServiceOption[M]

func WithListQuery added in v0.0.3

func WithListQuery[M Resource](query string, args ...interface{}) ServiceOption[M]

type ServiceQuery added in v0.0.3

type ServiceQuery struct {
	Filter string
	Args   []interface{}
}

type User added in v0.0.3

type User interface {
	IsAdmin() bool
	GetID() uint
}

type UserResourceAccessFunc added in v0.0.5

type UserResourceAccessFunc[M Resource] func(User, M) error

type UserService added in v0.0.3

type UserService interface {
	ListUsers(ctx context.Context) ([]User, error)
	CreateUser(ctx context.Context, user User) (User, error)
	GetUserByID(ctx context.Context, userID uint) (User, error)
	GetUserByCredentials(ctx context.Context, username, passwordHash string) (User, error)
	UpdateUserPassword(ctx context.Context, userID uint, password string) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL