fs

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2024 License: MIT Imports: 15 Imported by: 23

Documentation

Index

Constants

This section is empty.

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

View Source
var SystemSchemaTypes = []any{
	Role{},
	Permission{},
	User{},
	File{},
}

Functions

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() db.Client
	Resources() *ResourcesManager
	Reload(ctx context.Context, migration *db.Migration) (err error)
	Logger() logger.Logger
	UpdateCache(ctx context.Context) error
	Roles() []*Role
	Disk(names ...string) Disk
	Disks() []Disk

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

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

type Arg

type Arg struct {
	Type        ArgType `json:"type"`
	Required    bool    `json:"required"`
	Description string  `json:"description"`
	Example     any     `json:"example"`
}

type ArgType

type ArgType int

ArgType define the data type of a field

const (
	TypeInvalid ArgType = iota
	TypeBool
	TypeTime
	TypeJSON
	TypeUUID
	TypeBytes
	TypeEnum
	TypeString
	TypeText
	TypeInt8
	TypeInt16
	TypeInt32
	TypeInt
	TypeInt64
	TypeUint8
	TypeUint16
	TypeUint32
	TypeUint
	TypeUint64
	TypeFloat32
	TypeFloat64
)

func (ArgType) Common

func (t ArgType) Common() string

Common returns the common type of a field

func (ArgType) MarshalJSON

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

MarshalJSON marshal an enum value to the quoted json string value

func (ArgType) String

func (t ArgType) String() string

String returns the string representation of a type.

func (*ArgType) UnmarshalJSON

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

UnmarshalJSON unmashals a quoted json string to the enum value

func (ArgType) Valid

func (t ArgType) Valid() bool

Valid reports if the given type if known type.

type Args

type Args map[string]Arg

func (Args) Clone

func (a Args) Clone() Args

type Config

type Config struct {
	Dir               string
	AppKey            string
	Port              string
	BaseURL           string
	DashURL           string
	APIBaseName       string
	DashBaseName      string
	Logger            logger.Logger
	LoggerConfig      *logger.Config // If Logger is set, LoggerConfig will be ignored
	DB                db.Client
	DBConfig          *db.Config // If DB is set, DBConfig will be ignored
	StorageConfig     *StorageConfig
	HideResourcesInfo bool
	SystemSchemas     []any // types to build the system schemas
}

func (*Config) Clone

func (ac *Config) Clone() *Config

type Context

type Context interface {
	ID() string
	User() *User
	Value(string, ...any) (val any)
	Logger() 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 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

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      `` /* 137-byte string literal not displayed */
	URL       string     `json:"url,omitempty" fs:"-"`
	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:"-"`
	// contains filtered or unexported fields
}

File holds the file data

type HTTPResponse

type HTTPResponse struct {
	StatusCode int
	Body       []byte
	Header     http.Header
}

type Handler

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

Handler is a function that resolves a request

type HandlerFn

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

HandlerFn is a function that generates a resolver function

type Hooks

type Hooks struct {
	DBHooks     *db.Hooks
	PreResolve  []ResolveHook
	PostResolve []ResolveHook
}

Hooks is a struct that contains app hooks

type Map

type Map = map[string]any

Map is a shortcut for map[string]any

type Meta

type Meta struct {
	// Http method empty means the method is not set/allowed
	Get     string `json:"get,omitempty"`     // Only use for restful method GET
	Head    string `json:"head,omitempty"`    // Only use for restful method HEAD
	Post    string `json:"post,omitempty"`    // Only use for restful method POST
	Put     string `json:"put,omitempty"`     // Only use for restful method PUT
	Delete  string `json:"delete,omitempty"`  // Only use for restful method DELETE
	Connect string `json:"connect,omitempty"` // Only use for restful method CONNECT
	Options string `json:"options,omitempty"` // Only use for restful method OPTIONS
	Trace   string `json:"trace,omitempty"`   // Only use for restful method TRACE
	Patch   string `json:"patch,omitempty"`   // Only use for restful method PATCH

	Prefix     string     `json:"prefix,omitempty"` // Only use for group resource
	Args       Args       `json:"args,omitempty"`
	Public     bool       `json:"public,omitempty"`
	Signatures Signatures `json:"-"`
}

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

func (*Meta) Clone

func (m *Meta) Clone() *Meta

type Middleware

type Middleware func(c Context) error

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

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      `` /* 143-byte string literal not displayed */
	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 ResolveHook

type ResolveHook = Middleware

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

type Resource

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

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

func Connect

func Connect[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Connect is a shortcut to create a new resource with rest method CONNECT and using name as the connect path

func Delete

func Delete[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Delete is a shortcut to create a new resource with rest method DELETE and using name as the delete path

func Get

func Get[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Get is a shortcut to create a new resource with rest method GET and using name as the get path

func Head[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Head is a shortcut to create a new resource with rest method HEAD and using name as the head path

func NewResource

func NewResource[Input, Output any](
	name string,
	handler HandlerFn[Input, Output],
	metas ...*Meta,
) *Resource

NewResource creates a new resource with the given name, handler and meta

handler is a function that takes a context and an input and returns an output and an error
If the solver input type is not "any", the input will be parsed from the context

func Options

func Options[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Options is a shortcut to create a new resource with rest method OPTIONS and using name as the options path

func Patch

func Patch[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Patch is a shortcut to create a new resource with rest method PATCH and using name as the patch path

func Post

func Post[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Post is a shortcut to create a new resource with rest method POST and using name as the post path

func Put

func Put[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Put is a shortcut to create a new resource with rest method PUT and using name as the put path

func Trace

func Trace[Input, Output any](name string, handler HandlerFn[Input, Output], metas ...*Meta) *Resource

Trace is a shortcut to create a new resource with rest method TRACE and using name as the trace path

func (*Resource) Add

func (r *Resource) Add(resources ...*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, handler Handler, metas ...*Meta) (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, metas ...*Meta) (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) Handler

func (r *Resource) Handler() Handler

Handler returns the resolver of the 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) IsPublic

func (r *Resource) IsPublic() bool

IsPublic returns true if the resource is white listed

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) Resources

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

Resources returns the sub resources of the resource

func (*Resource) Signature

func (r *Resource) Signature() Signatures

Signature returns the signature of the resource

func (*Resource) String

func (r *Resource) String() string

String returns a string representation of the resource

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) Clone

func (rs *ResourcesManager) Clone() *ResourcesManager

Clone clones the resource manager and all sub resources

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" fs:"optional"`
	Root        bool          `json:"root,omitempty" fs:"optional"`
	Users       []*User       `json:"users,omitempty" fs.relation:"{'type':'m2m','schema':'user','field':'roles','owner':true}"`
	Permissions []*Permission `json:"permissions,omitempty" fs.relation:"{'type':'o2m','schema':'permission','field':'role','owner':true}"`

	CreatedAt *time.Time `json:"created_at,omitempty" fs:"default=NOW()"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// contains filtered or unexported fields
}

Role is a struct that contains the role data

type Signature

type Signature struct {
	Type any
	Name string
}

Signature hold the information of a signature

type Signatures

type Signatures = []any

Signatures hold the input and output types of a resolver

  • The first element is the input type

  • The second element is the output type

  • Each element is a type of any or a *Signature

For example:

- []any{&LoginData{}, &LoginResponse{}} // The input type is *LoginData and the output type is *LoginResponse

- []any{int, string} // The input type is int and the output type is string

- []any{&Signature{Type: dynamicStruct, Name: "Dynamic"}, int}: dynamic struct doesn't have name, use *Signature to define it

type StaticFs

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

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" fs:"optional"`
	Password string `json:"password,omitempty" fs:"optional"`

	Active           bool   `json:"active,omitempty" fs:"optional"`
	Provider         string `json:"provider,omitempty" fs:"optional"`
	ProviderID       string `json:"provider_id,omitempty" fs:"optional"`
	ProviderUsername string `json:"provider_username,omitempty" fs:"optional"`

	RoleIDs []uint64 `json:"role_ids,omitempty"`
	Roles   []*Role  `json:"roles,omitempty" fs.relation:"{'type':'m2m','schema':'role','field':'users','owner':false}"`
	Files   []*File  `json:"files,omitempty" fs.relation:"{'type':'o2m','schema':'file','field':'user','owner':true}"`

	CreatedAt *time.Time `json:"created_at,omitempty"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// contains filtered or unexported fields
}

User is a struct that contains user data

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