app

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const DELETE = "DELETE"
View Source
const GET = "GET"
View Source
const OPTIONS = "OPTIONS"
View Source
const PATCH = "PATCH"
View Source
const POST = "POST"
View Source
const PUT = "PUT"

Variables

View Source
var AllowedFileTypes = []string{
	"text/xml",
	"text/xml; charset=utf-8",
	"text/plain",
	"text/plain; charset=utf-8",
	"image/svg+xml",
	"image/jpeg",
	"image/pjpeg",
	"image/png",
	"image/gif",
	"image/x-icon",
	"application/pdf",
	"application/msword",
	"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
	"application/powerpoint",
	"application/x-mspowerpoint",
	"application/vnd.openxmlformats-officedocument.presentationml.presentation",
	"application/mspowerpoint",
	"application/vnd.ms-powerpoint",
	"application/vnd.openxmlformats-officedocument.presentationml.slideshow",
	"application/vnd.oasis.opendocument.text",
	"application/excel",
	"application/vnd.ms-excel",
	"application/x-excel",
	"application/x-msexcel",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",

	"audio/mpeg3",
	"audio/x-mpeg-3",
	"video/x-mpeg",
	"audio/m4a",
	"audio/ogg",
	"audio/wav",
	"audio/x-wav",
	"video/mp4",
	"video/x-m4v",
	"video/quicktime",
	"video/x-ms-asf",
	"video/x-ms-wmv",
	"application/x-troff-msvideo",
	"video/avi",
	"video/msvideo",
	"video/x-msvideo",
	"audio/mpeg",
	"video/mpeg",
	"video/ogg",
	"video/3gpp",
	"audio/3gpp",
	"video/3gpp2",
	"audio/3gpp2",
}

AllowedFileTypes is a list of allowed file types

View Source
var GuestUser = &User{
	ID:       0,
	Username: "",
	Roles:    []*Role{RoleGuest},
}

GuestUser is the guest user

View Source
var (
	// PermissionTypeToStrings is a map that contains the string representation of the enum values
	PermissionTypeToStrings = [...]string{
		PermissionTypeInvalid: "invalid",
		PermissionTypeAllow:   "allow",
		PermissionTypeDeny:    "deny",
	}
)
View Source
var RoleAdmin = &Role{
	ID:   1,
	Name: "Admin",
	Root: true,
}

RoleAdmin is the admin role

View Source
var RoleGuest = &Role{
	ID:   3,
	Name: "Guest",
	Root: false,
}

RoleGuest is the guest role

View Source
var RoleUser = &Role{
	ID:   2,
	Name: "User",
	Root: false,
}

RoleUser is the user role

Functions

func IsNotFound added in v0.0.5

func IsNotFound(err error) bool

func PermissionTypeValues

func PermissionTypeValues() []string

PermissionTypeValues returns all possible values of the enum.

Types

type App

type App interface {
	Key() string
	SchemaBuilder() *schema.Builder
	DB() DBClient
	Resources() *ResourcesManager
	Reload(migration *Migration) (err error)
	Logger() Logger
	UpdateCache() error
	Roles() []*Role
	Disk(names ...string) Disk
	Disks() []Disk

	AddResource(resource *Resource)
	AddMiddlewares(hooks ...Middleware)
	Hooks() *Hooks
	OnPreResolve(hooks ...Middleware)
	OnPostResolve(hooks ...Middleware)
	OnPostDBGet(PostDBGetHook)
}

App is the interface that defines the methods that an app must implement

type Context

type Context interface {
	ID() string
	User() *User
	Value(string, ...any) (val any)
	Logger() Logger
	Parse(any) error
	Context() context.Context
	Args() map[string]string
	Arg(string, ...string) string
	ArgInt(string, ...int) int
	Entity() (*schema.Entity, error)
	Resource() *Resource
	AuthToken() string
	Next() error
	Result(...*Result) *Result
	Files() ([]*File, error)
}

Context is the interface that defines the methods that a context must implement

type CountOption added in v0.0.5

type CountOption struct {
	Column string
	Unique bool
}

type DBClient added in v0.0.5

type DBClient interface {
	Dialect() string
	Exec(ctx context.Context, query string, args any, bindValue any) error
	Rollback() error
	Commit() error
	CreateDBModel(s *schema.Schema, rs ...*schema.Relation) Model
	Tx(ctx context.Context) (DBClient, error)
	IsTx() bool
	Model(name string) (Model, error)
	Close() error
	SchemaBuilder() *schema.Builder
	Reload(newSchemaBuilder *schema.Builder, migration *Migration) (DBClient, error)
	DB() *sql.DB
	Config() *DBConfig
	Hooks() *Hooks
}

type DBConfig added in v0.0.5

type DBConfig struct {
	Driver          string
	Name            string
	Host            string
	Port            string
	User            string
	Pass            string
	Logger          Logger
	LogQueries      bool
	MigrationDir    string
	IgnoreMigration bool
	Hooks           func() *Hooks
}

func (*DBConfig) Clone added in v0.0.5

func (c *DBConfig) Clone() *DBConfig

type Disk

type Disk interface {
	Name() string
	Root() string
	URL(filepath string) string
	Delete(c context.Context, filepath string) error
	Put(c context.Context, file *File) (*File, error)
	PutReader(c context.Context, in io.Reader, size uint64, mime, dst string) (*File, error)
	PutMultipart(c context.Context, m *multipart.FileHeader, dsts ...string) (*File, error)
	LocalPublicPath() string
}

Disk is the interface that defines the methods that a disk must implement

type DiskConfig

type DiskConfig struct {
	Name            string        `json:"name"`
	Driver          string        `json:"driver"`
	Root            string        `json:"root"`
	BaseURL         string        `json:"base_url"`
	PublicPath      string        `json:"public_path"`
	GetBaseURL      func() string `json:"-"`
	Provider        string        `json:"provider"`
	Endpoint        string        `json:"endpoint"`
	Region          string        `json:"region"`
	Bucket          string        `json:"bucket"`
	AccessKeyID     string        `json:"access_key_id"`
	SecretAccessKey string        `json:"secret_access_key"`
	ACL             string        `json:"acl"`
}

DiskConfig holds the disk configuration

func (*DiskConfig) Clone added in v0.0.3

func (dc *DiskConfig) Clone() *DiskConfig

Clone returns a clone of the disk configuration

type File

type File struct {
	ID        uint64     `json:"id,omitempty"`
	Disk      string     `json:"disk,omitempty"`
	Name      string     `json:"name,omitempty"`
	Path      string     `json:"path,omitempty"`
	Type      string     `json:"type,omitempty"`
	Size      uint64     `json:"size,omitempty"`
	UserID    uint64     `json:"user_id,omitempty"`
	User      *User      `json:"user,omitempty"`
	URL       string     `json:"url,omitempty"`
	CreatedAt *time.Time `json:"created_at,omitempty"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	Reader    io.Reader  `json:"-"`
}

File holds the file data

func EntitiesToFiles

func EntitiesToFiles(entities []*schema.Entity, disks ...Disk) []*File

EntitiesToFiles converts entities to files

func EntityToFile

func EntityToFile(e *schema.Entity, disks ...Disk) *File

EntityToFile converts an entity to a file

type Hooks

type Hooks struct {
	PreResolve  []ResolveHook
	PostResolve []ResolveHook
	PostDBGet   []PostDBGetHook
}

Hooks is a struct that contains app hooks

type LogContext added in v0.0.5

type LogContext Map

type Logger added in v0.0.5

type Logger interface {
	Info(...any)
	Infof(string, ...any)
	Error(...any)
	Errorf(string, ...any)
	Debug(...any)
	Fatal(...any)
	Warn(...any)
	Panic(...any)
	DPanic(...any)
	WithContext(context LogContext, callerSkips ...int) Logger
}

type Map

type Map map[string]any

Map is a shortcut for map[string]any

type Meta

type Meta Map

Meta hold extra data, ex: request method, path, etc

type Middleware

type Middleware func(c Context) error

Middleware is a function that can be used to add middleware to a resource

type Migration added in v0.0.5

type Migration struct {
	Dir          string
	RenameTables []*RenameItem
	RenameFields []*RenameItem
}

type MockLogger added in v0.0.5

type MockLogger struct {
	Silence  bool
	Messages []*MockLoggerMessage
}

func CreateMockLogger added in v0.0.5

func CreateMockLogger(silences ...bool) *MockLogger

func (*MockLogger) DPanic added in v0.0.5

func (l *MockLogger) DPanic(params ...any)

func (*MockLogger) Debug added in v0.0.5

func (l *MockLogger) Debug(params ...any)

func (*MockLogger) Error added in v0.0.5

func (l *MockLogger) Error(params ...any)

func (*MockLogger) Errorf added in v0.0.5

func (l *MockLogger) Errorf(msg string, params ...any)

func (*MockLogger) Fatal added in v0.0.5

func (l *MockLogger) Fatal(params ...any)

func (*MockLogger) Info added in v0.0.5

func (l *MockLogger) Info(params ...any)

func (*MockLogger) Infof added in v0.0.5

func (l *MockLogger) Infof(msg string, params ...any)

func (*MockLogger) Last added in v0.0.5

func (l *MockLogger) Last() MockLoggerMessage

func (*MockLogger) Panic added in v0.0.5

func (l *MockLogger) Panic(params ...any)

func (*MockLogger) Warn added in v0.0.5

func (l *MockLogger) Warn(params ...any)

func (*MockLogger) WithContext added in v0.0.5

func (l *MockLogger) WithContext(context LogContext, callerSkips ...int) Logger

type MockLoggerMessage added in v0.0.5

type MockLoggerMessage struct {
	Type   string `json:"type"`
	Params []any  `json:"params"`
}

func (MockLoggerMessage) String added in v0.0.5

func (m MockLoggerMessage) String() string

type Model added in v0.0.5

type Model interface {
	Query(predicates ...*Predicate) Query
	Mutation(skipTxs ...bool) Mutation
	Schema() *schema.Schema
	CreateFromJSON(json string) (id uint64, err error)
	Create(e *schema.Entity) (id uint64, err error)
	SetClient(client DBClient) Model
	Clone() Model
}

type Mutation added in v0.0.5

type Mutation interface {
	Where(predicates ...*Predicate) Mutation
	GetRelationEntityIDs(fieldName string, fieldValue any) ([]driver.Value, error)
	Create(e *schema.Entity) (id uint64, err error)
	Update(e *schema.Entity) (affected int, err error)
	Delete() (affected int, err error)
}

type NotFoundError added in v0.0.5

type NotFoundError struct {
	Message string
}

func (*NotFoundError) Error added in v0.0.5

func (e *NotFoundError) Error() string

type OperatorType added in v0.0.5

type OperatorType int

OperatorType is the type of the operator

const (
	OpInvalid OperatorType = iota
	OpEQ
	OpNEQ
	OpGT
	OpGTE
	OpLT
	OpLTE
	OpLIKE
	OpIN
	OpNIN
	OpNULL
)

func (OperatorType) MarshalJSON added in v0.0.5

func (t OperatorType) MarshalJSON() ([]byte, error)

MarshalJSON marshal an enum value to the quoted json string value

func (OperatorType) String added in v0.0.5

func (t OperatorType) String() string

String returns the string representation of a type.

func (*OperatorType) UnmarshalJSON added in v0.0.5

func (t *OperatorType) UnmarshalJSON(b []byte) error

UnmarshalJSON unmashals a quoted json string to the enum value

func (OperatorType) Valid added in v0.0.5

func (t OperatorType) Valid() bool

Valid reports if the given type if known type.

type Pagination

type Pagination struct {
	Pagination *PaginationInfo `json:"pagination"`
	Data       any             `json:"data"`
}

Pagination is a struct that contains pagination info and the data

func NewPagination

func NewPagination(total, perPage, currentPage uint, data any) *Pagination

NewPagination creates a new pagination struct

type PaginationInfo added in v0.0.5

type PaginationInfo struct {
	Total       uint `json:"total"`
	PerPage     uint `json:"per_page"`
	CurrentPage uint `json:"current_page"`
	LastPage    uint `json:"last_page"`
}

PaginationInfo is a struct that contains pagination data

type Permission

type Permission struct {
	ID       int    `json:"id,omitempty"`
	RoleID   int    `json:"role_id,omitempty"`
	Resource string `json:"resource,omitempty"`
	Value    string `json:"value,omitempty"`
	Role     *Role  `json:"role,omitempty"`

	CreatedAt *time.Time `json:"created_at,omitempty"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	DeletedAt *time.Time `json:"Deleted_at,omitempty"`
}

Permission is a struct that contains the permission data

type PermissionType

type PermissionType uint

PermissionType is an enum that represents the type of a permission

const (
	PermissionTypeInvalid PermissionType = iota
	PermissionTypeAllow
	PermissionTypeDeny
)

func GetPermissionTypeFromName

func GetPermissionTypeFromName(name string) PermissionType

GetPermissionTypeFromName returns the type from a string.

func (PermissionType) MarshalJSON

func (p PermissionType) MarshalJSON() ([]byte, error)

MarshalJSON marshal an enum value to the quoted json string value

func (PermissionType) String

func (p PermissionType) String() string

String returns the string representation of a type.

func (*PermissionType) UnmarshalJSON

func (p *PermissionType) UnmarshalJSON(b []byte) error

UnmarshalJSON unmashals a quoted json string to the enum value

func (PermissionType) Valid

func (p PermissionType) Valid() bool

Valid reports if the given type if known type.

type PostDBGetHook added in v0.0.5

type PostDBGetHook = func(query *QueryOption, entities []*schema.Entity) ([]*schema.Entity, error)

type Predicate added in v0.0.5

type Predicate struct {
	Field              string
	Operator           OperatorType
	Value              any
	RelationFieldNames []string
	And                []*Predicate
	Or                 []*Predicate
}

func And added in v0.0.5

func And(predicates ...*Predicate) *Predicate

func CreatePredicatesFromFilterObject added in v0.0.5

func CreatePredicatesFromFilterObject(
	sb *schema.Builder,
	s *schema.Schema,
	filterObject string,
) ([]*Predicate, error)

CreatePredicateFromFilterObject creates a predicate from a filter object A filter object is a JSON object that contains the filter for the query E.g.

{
	"approved": true,
	"status": "online",
	"name": {
		"$like": "test%",
		"$neq": "test2"
	},
	"age": {
		"$gt": 1,
		"$lt": 10
	},
	"$or": [
		{
			"age": 1
		},
		{
			"bio": {
				"$like": "test%",
				"$neq": "test2"
			}
		},
		{
			"status": "offline"
		},
		{
			"$and": [
				{
					"bio": {
						"$neq": "test",
						"$like": "%a"
					}
				},
				{
					"age": {
						"$gt": 1
					}
				}
			]
		}
	]
}

will be converted to "entgo.io/ent/dialect/sql" sql.And(

sql.EQ("approved", true),
sql.EQ("status", "online"),
sql.And(
	sql.Like("name", "test%"),
	sql.NEQ("name", "test2"),
),
sql.And(
	sql.GT("age", 1),
	sql.LT("age", 10),
),
sql.Or(
	sql.EQ("age", 1),
	sql.And(
		sql.Like("bio", "test%"),
		sql.NEQ("bio", "test2"),
	),
	sql.EQ("status", "offline"),
	sql.And(
		sql.NEQ("bio", "test"),
		sql.Like("bio", "%a"),
		sql.GT("age", 1),
	),
),

)

func EQ added in v0.0.5

func EQ(field string, value any, relationFields ...string) *Predicate

func GT added in v0.0.5

func GT(field string, value any, relationFields ...string) *Predicate

func GTE added in v0.0.5

func GTE(field string, value any, relationFields ...string) *Predicate

func In added in v0.0.5

func In(field string, values []any, relationFields ...string) *Predicate

func IsFalse added in v0.0.5

func IsFalse(field string, relationFields ...string) *Predicate

func IsTrue added in v0.0.5

func IsTrue(field string, relationFields ...string) *Predicate

func LT added in v0.0.5

func LT(field string, value any, relationFields ...string) *Predicate

func LTE added in v0.0.5

func LTE(field string, value any, relationFields ...string) *Predicate

func Like added in v0.0.5

func Like(field string, value string, relationFields ...string) *Predicate

func NEQ added in v0.0.5

func NEQ(field string, value any, relationFields ...string) *Predicate

func NotIn added in v0.0.5

func NotIn(field string, values []any, relationFields ...string) *Predicate

func Null added in v0.0.5

func Null(field string, value bool, relationFields ...string) *Predicate

func Or added in v0.0.5

func Or(predicates ...*Predicate) *Predicate

func (*Predicate) Clone added in v0.0.5

func (p *Predicate) Clone() *Predicate

type Query added in v0.0.5

type Query interface {
	Where(predicates ...*Predicate) Query
	Limit(limit uint) Query
	Offset(offset uint) Query
	Select(columns ...string) Query
	Order(order ...string) Query
	Count(options *CountOption, ctxs ...context.Context) (int, error)
	Get(ctxs ...context.Context) ([]*schema.Entity, error)
	First(ctxs ...context.Context) (*schema.Entity, error)
	Only(ctxs ...context.Context) (*schema.Entity, error)
	Options() *QueryOption
}

type QueryOption added in v0.0.5

type QueryOption struct {
	Limit      uint         `json:"limit"`
	Offset     uint         `json:"offset"`
	Columns    []string     `json:"columns"`
	Order      []string     `json:"order"`
	Predicates []*Predicate `json:"predicates"`
	Model      Model        `json:"-"`
}

type RenameItem added in v0.0.5

type RenameItem struct {
	Type            string `json:"type"` // "column" or "table"
	From            string `json:"from"`
	To              string `json:"to"`
	IsJunctionTable bool   `json:"is_junction_table,omitempty"` // use in rename table: If the table is a junction table
	SchemaName      string `json:"schema,omitempty"`            // use in rename column: The schema name of the column
	SchemaNamespace string `json:"schema_namespace,omitempty"`  // use in rename column: The schema name of the column
}

type ResolveHook

type ResolveHook = Middleware

ResolveHook is a function that can be used to add hooks to a resource

type Resolver

type Resolver func(c Context) (any, error)

Resolver is a function that resolves a request

type ResolverGenerator

type ResolverGenerator[Input, Output any] func(c Context, input *Input) (Output, error)

ResolverGenerator is a function that generates a resolver function

type Resource

type Resource struct {
	// contains filtered or unexported fields
}

Resource is a resource that can be used to define a resource tree

func NewResource

func NewResource[Input, Output any](
	name string,
	resolverGenerator ResolverGenerator[Input, Output],
	extras ...any,
) *Resource

NewResource creates a new resource

func (*Resource) Add

func (r *Resource) Add(resource *Resource) (self *Resource)

Add adds a new resource to the current resource as a child and returns the current resource

func (*Resource) AddResource

func (r *Resource) AddResource(name string, resolver Resolver, extras ...any) (self *Resource)

AddResource adds a new resource to the current resource as a child and returns the current resource extras can be used to pass additional information to the resource. Currently supported extras are:

  • *Meta: used to pass meta information to the resource, example: &Meta{"rest.POST": "/login"}
  • *Signature: used to pass input and output signatures to the resource, example: &Signature{Input: LoginData{}, Output: LoginResponse{}}

func (*Resource) Clone

func (r *Resource) Clone() *Resource

Clone clones the resource and all sub resources

func (*Resource) Find

func (r *Resource) Find(resourceID string) *Resource

Find returns the resource with the given id The id is in the format of "group1.group2.group3.resource" While group1, group2 and group3 are name of the groups and resource is the name of the resource

func (*Resource) Group

func (r *Resource) Group(name string, resources ...*Resource) (group *Resource)

Group creates a new resource group and adds it to the current resource as a child and returns the group resource

func (*Resource) ID

func (r *Resource) ID() string

ID returns the id of the resource

func (*Resource) Init

func (r *Resource) Init() error

Init validates the resource and all sub resources

func (*Resource) IsGroup

func (r *Resource) IsGroup() bool

IsGroup returns true if the resource is a group

func (*Resource) MarshalJSON

func (r *Resource) MarshalJSON() ([]byte, error)

MarshalJSON marshals the resource to json

func (*Resource) Meta

func (r *Resource) Meta() Meta

Meta returns the meta of the resource

func (*Resource) Name

func (r *Resource) Name() string

Name returns the name of the resource

func (*Resource) Print

func (r *Resource) Print()

Print prints the resource and all sub resources

func (*Resource) Remove

func (r *Resource) Remove(resource *Resource) (self *Resource)

func (*Resource) Resolver

func (r *Resource) Resolver() Resolver

Resolver returns the resolver of the resource

func (*Resource) Resources

func (r *Resource) Resources() []*Resource

Resources returns the sub resources of the resource

func (*Resource) String

func (r *Resource) String() string

String returns a string representation of the resource

func (*Resource) WhiteListed

func (r *Resource) WhiteListed() bool

WhiteListed returns true if the resource is white listed

type ResourcesManager

type ResourcesManager struct {
	*Resource
	Middlewares []Middleware
	Hooks       func() *Hooks
}

ResourcesManager is a resource manager that can be used to manage resources

func NewResourcesManager

func NewResourcesManager() *ResourcesManager

NewResourcesManager creates a new resources manager

func (*ResourcesManager) Init

func (rs *ResourcesManager) Init() error

Init validates the resource and all sub resources

type Result

type Result struct {
	Error *errors.Error `json:"error,omitempty"`
	Data  any           `json:"data,omitempty"`
}

Result is a struct that contains the result of a resolver

func NewResult

func NewResult(data any, err error) *Result

NewResult creates a new result struct

type Role

type Role struct {
	ID          uint64        `json:"id,omitempty"`
	Name        string        `json:"name,omitempty"`
	Description string        `json:"description,omitempty"`
	Root        bool          `json:"root,omitempty"`
	Users       []*User       `json:"users,omitempty"`
	Permissions []*Permission `json:"permissions,omitempty"`

	CreatedAt *time.Time `json:"created_at,omitempty"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
}

Role is a struct that contains the role data

func EntitiesToRoles added in v0.0.5

func EntitiesToRoles(entities []*schema.Entity) []*Role

EntitiesToRoles converts entities to roles

func EntityToRole

func EntityToRole(e *schema.Entity) *Role

EntityToRole converts an entity to a role

type Signature

type Signature = [2]any

Signature hold the input and output types of a resolver

type StaticFs added in v0.0.5

type StaticFs struct {
	Root       http.FileSystem
	BasePath   string
	PathPrefix string
}

type StorageConfig

type StorageConfig struct {
	DefaultDisk string        `json:"default_disk"`
	DisksConfig []*DiskConfig `json:"disks"`
}

StorageConfig holds the storage configuration

func (*StorageConfig) Clone added in v0.0.3

func (sc *StorageConfig) Clone() *StorageConfig

Clone returns a clone of the storage configuration

type User

type User struct {
	ID       uint64 `json:"id,omitempty"`
	Username string `json:"username,omitempty"`
	Email    string `json:"email,omitempty"`
	Password string `json:"password,omitempty"`

	Provider         string `json:"provider,omitempty"`
	ProviderID       string `json:"provider_id,omitempty"`
	ProviderUsername string `json:"provider_username,omitempty"`

	RoleIDs []uint64 `json:"role_ids,omitempty"`
	Roles   []*Role  `json:"roles,omitempty"`
	Active  bool     `json:"active,omitempty"`

	CreatedAt *time.Time `json:"created_at,omitempty"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
}

User is a struct that contains user data

func EntityToUser

func EntityToUser(e *schema.Entity) *User

EntityToUser converts an entity to a user

func (*User) IsRoot

func (u *User) IsRoot() bool

func (*User) JwtClaim

func (u *User) JwtClaim(key string, exps ...time.Time) (string, time.Time, error)

JwtClaim generates a jwt claim

type UserJwtClaims

type UserJwtClaims struct {
	jwt.RegisteredClaims
	User *User `json:"user"`
}

UserJwtClaims is a struct that contains the user jwt claims

Jump to

Keyboard shortcuts

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