app

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2023 License: MIT Imports: 41 Imported by: 0

Documentation

Overview

app merupakan class atau fungsi atau variabel umum yang dipakai pada sebagian besar API.

Index

Constants

View Source
const (
	TestInvalidToken        = "invalidToken"
	TestForbiddenToken      = "forbiddenToken"
	TestReadOnlyToken       = "detail,list"
	TestCreateReadOnlyToken = "detail,list,create"
	TestEditReadOnlyToken   = "detail,list,edit"
	TestDeleteReadOnlyToken = "detail,list,delete"
	TestFullAccessToken     = "fullAccessToken"
)
View Source
const CtxKey = "ctx"

Variables

View Source
var (
	APP_VERSION = "23.03.161330"

	APP_ENV  = "local"
	APP_PORT = "4001"
	APP_URL  = "http://localhost:4001"

	IS_MAIN_SERVER = true // set to true to run migration, seed and task scheduling

	IS_GENERATE_OPEN_API_DOC = false

	// for testing
	ENV_FILE            = ""
	IS_USE_MOCK_SERVICE = false
	IS_USE_MOCK_DB      = false

	LOG_CONSOLE_ENABLED     = true           // print log to the terminal
	LOG_FILE_ENABLED        = true           // log to a file. the fields below can be skipped if this value is false
	LOG_FILE_USE_LOCAL_TIME = true           // if false log rotation filename will be use UTC time
	LOG_FILE_FILENAME       = "logs/api.log" //
	LOG_FILE_MAX_SIZE       = 100            // MB
	LOG_FILE_MAX_AGE        = 7              // days
	LOG_FILE_MAX_BACKUPS    = 0              // files

	JWT_KEY     = "f4cac8b77a8d4cb5881fac72388bb226"
	CRYPTO_KEY  = "wAGyTpFQX5uKV3JInABXXEdpgFkQLPTf"
	CRYPTO_SALT = "0de0cda7d2dd4937a1c4f7ddc43c580f"
	CRYPTO_INFO = "info"

	DB_DRIVER            = "postgres"
	DB_HOST              = "127.0.0.1"
	DB_HOST_READ         = ""
	DB_PORT              = 5432
	DB_DATABASE          = "data.db"
	DB_USERNAME          = "postgres"
	DB_PASSWORD          = "secret"
	DB_MAX_OPEN_CONNS    = 0
	DB_MAX_IDLE_CONNS    = 5
	DB_CONN_MAX_LIFETIME = time.Hour // on .env = "1h". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
	DB_IS_DEBUG          = false

	REDIS_HOST      = "127.0.0.1"
	REDIS_PORT      = "6379"
	REDIS_CACHE_DB  = 3
	REDIS_REPORT_DB = 3
	REDIS_USERNAME  = ""
	REDIS_PASSWORD  = ""

	FS_DRIVER          = "local"
	FS_LOCAL_DIR_PATH  = "storages"
	FS_PUBLIC_DIR_PATH = "storages"
	FS_END_POINT       = "s3.amazonaws.com"
	FS_PORT            = 443
	FS_REGION          = "ap-southeast-3"
	FS_BUCKET_NAME     = "attachments"
	FS_ACCESS_KEY      = ""
	FS_SECRET_KEY      = ""

	TELEGRAM_ALERT_TOKEN   = ""
	TELEGRAM_ALERT_USER_ID = ""
)

default config

Functions

func Config

func Config()

func ErrorHandler

func ErrorHandler(c *fiber.Ctx, err error) error

func Find

func Find(db *gorm.DB, model ModelInterface, query url.Values) ([]map[string]any, error)

func First

func First(db *gorm.DB, model ModelInterface, query url.Values) error

func Logger

func Logger() *loggerUtil

func Mock

func Mock() *mockUtil

add your mock service here, for example :

// original func (add IS_USE_MOCK_SERVICE_ABC and IS_USE_MOCK_SUCCESS to config)
func (*mockHandler) CallServiceABC(ctx *Ctx, param RequestServiceABC) (ResponseServiceABC, error) {
	if IS_USE_MOCK_SERVICE_ABC {
		return Mock().CallServiceABC(ctx, param)
	}
	var err error
	res := ResponseServiceABC{}
	// do something here
	return res, err
}

// mock func
func (*mockHandler) CallServiceABC(ctx *Ctx, param RequestServiceABC) (ResponseServiceABC, error) {
	if IS_USE_MOCK_SUCCESS  {
		// return success dummy
	}
	return ResponseServiceABC{}, NewError(http.StatusInternalServerError, "Something wrong")
}

func NewCrypto

func NewCrypto(keys ...string) *cryptoUtil

func NewError

func NewError(statusCode int, message string, detail ...any) *grest.Error

func NotFoundHandler

func NotFoundHandler(c *fiber.Ctx) error

func OpenAPI

func OpenAPI() *openAPIUtil

func OpenAPIError

func OpenAPIError() *openAPIError

func PaginationInfo

func PaginationInfo(db *gorm.DB, model ModelInterface, query url.Values) (int64, int, int, int, error)

func ParseQuery

func ParseQuery(c *fiber.Ctx) url.Values

func Recover

func Recover(c *fiber.Ctx) (err error)

func Test added in v0.0.12

func Test() *testUtil

func VersionHandler

func VersionHandler(c *fiber.Ctx) error

Types

type Action

type Action struct {
	Method   string
	EndPoint string
	DataID   string
}

type CacheInterface

type CacheInterface interface {
	Get(key string, val any) error
	Set(key string, val any, e ...time.Duration) error
	Delete(key string) error
	DeleteWithPrefix(prefix string) error
	Invalidate(prefix string, keys ...string)
	Clear() error
}

func Cache

func Cache() CacheInterface

type CryptoInterface

type CryptoInterface interface {
	NewToken() string
	NewHash(text string, cost ...int) (string, error)
	CompareHash(hashed, text string) error
	NewJWT(claims any) (string, error)
	ParseAndVerifyJWT(token string, claims any) error
	Encrypt(text string) (string, error)
	Decrypt(text string) (string, error)
	GenerateKey() ([]byte, error)
	PKCS5Padding(ciphertext []byte, blockSize int) []byte
	PKCS5Unpadding(encrypt []byte) ([]byte, error)
}

func Crypto

func Crypto() CryptoInterface

type Ctx

type Ctx struct {
	Lang   string // bahasa yang digunakan oleh user ybs
	Action Action // informasi umum terkait request

	IsAsync bool // for async use, autocommit
	// contains filtered or unexported fields
}

func (Ctx) DB

func (c Ctx) DB(connName ...string) (*gorm.DB, error)

func (Ctx) Hook

func (c Ctx) Hook(method, reason, id string, old any)

func (Ctx) NotFoundError

func (c Ctx) NotFoundError(err error, entity, key, value string) error

func (Ctx) Trans

func (c Ctx) Trans(key string, params ...map[string]string) string

Trans memberikan translasi atas key dan params sesuai dengan bahasa yang sedang digunakan user.

func (*Ctx) TxBegin

func (c *Ctx) TxBegin() error

Begin db transaction, dipanggil dari middleware sebelum masuk ke handler.

func (*Ctx) TxCommit

func (c *Ctx) TxCommit()

Commit db transaction, dipanggil dari middleware setelah dari handler ketika response nya berhasil (2xx).

func (*Ctx) TxRollback

func (c *Ctx) TxRollback()

Rollback db transaction, dipanggil dari middleware setelah dari handler ketika response nya error (selain 2xx).

func (Ctx) ValidateParam

func (c Ctx) ValidateParam(v any) error

ValidateParam melakukan validasi atas payload yang dikirim.

func (Ctx) ValidatePermission

func (c Ctx) ValidatePermission(aclKey string) error

ValidateAuth melakukan validasi apakah permintaan dilakukan oleh user yang berwenang atau tidak.

type DBInterface

type DBInterface interface {
	RegisterConn(connName string, conn *gorm.DB)
	Conn(connName string) (*gorm.DB, error)
	Close()
	RegisterTable(connName string, t grest.Table) error
	MigrateTable(tx *gorm.DB, connName string, mTable grest.MigrationTable) error
	RegisterSeeder(connName, seederKey string, seederHandler grest.SeederHandler) error
	RunSeeder(tx *gorm.DB, connName string, seedTable grest.SeederTable) error
	Connect(connName string, c grest.DBConfig) error
	IsNotFoundError(err error) bool
}

func DB

func DB() DBInterface

type FSInterface

type FSInterface interface {
	GetFileUrl(fileName string, path ...string) string
	Upload(fileName string, src io.Reader, fileSize int64, opts ...FileUploadOption) (FileUploadInfo, error)
	Delete(fileName string, opts ...FileDeleteOption) error
}

func FS

func FS() FSInterface

type FileDeleteOption

type FileDeleteOption struct {
	minio.RemoveObjectOptions
}

type FileUploadInfo

type FileUploadInfo struct {
	minio.UploadInfo
}

type FileUploadOption

type FileUploadOption struct {
	minio.PutObjectOptions
}

type HttpClientInterface

type HttpClientInterface interface {
	Debug()
	AddHeader(key, value string)
	AddMultipartBody(body any) error
	AddUrlEncodedBody(body any) error
	AddJsonBody(body any) error
	AddXmlBody(body any) error
	SetTimeout(timeout time.Duration)
	Send() (*http.Response, error)
	BodyResponseStr() string
	UnmarshalJson(v any) error
	UnmarshalXml(v any) error
}

func HttpClient

func HttpClient(method, url string) HttpClientInterface

type ListModel

type ListModel struct {
	Count       int64 `json:"count"`
	PageContext struct {
		Page      int `json:"page"`
		PerPage   int `json:"per_page"`
		PageCount int `json:"total_pages"`
	} `json:"page_context"`
	Links struct {
		First    string `json:"first"`
		Previous string `json:"previous"`
		Next     string `json:"next"`
		Last     string `json:"last"`
	} `json:"links"`
	Data []map[string]any `json:"results"`
}

func (*ListModel) SetData

func (list *ListModel) SetData(data []map[string]any, query url.Values)
func (list *ListModel) SetLink(c *fiber.Ctx)

type Model

type Model struct {
	grest.Model
}

type ModelInterface

type ModelInterface interface {
	grest.ModelInterface
}

type NullBool

type NullBool struct {
	grest.NullBool
}

NullBool is nullable Bool, it embeds a grest.NullBool, so you can add your own method or override grest.NullBool method

func NewNullBool

func NewNullBool(val bool) NullBool

NewNullBool return NullBool

type NullDate

type NullDate struct {
	grest.NullDate
}

NullDate is nullable Date, it embeds a grest.NullDate, so you can add your own method or override grest.NullDate method

func NewNullDate

func NewNullDate(val time.Time) NullDate

NewNullDate return NullDate

type NullDateTime

type NullDateTime struct {
	grest.NullDateTime
}

NullDateTime is nullable DateTime, it embeds a grest.NullDateTime, so you can add your own method or override grest.NullDateTime method

func NewNullDateTime

func NewNullDateTime(val time.Time) NullDateTime

NewNullDateTime return NullDateTime

type NullFloat64

type NullFloat64 struct {
	grest.NullFloat64
}

NullFloat64 is nullable Float64, it embeds a grest.NullFloat64, so you can add your own method or override grest.NullFloat64 method

func NewNullFloat64

func NewNullFloat64(val float64) NullFloat64

NewNullFloat64 return NullFloat64

type NullInt64

type NullInt64 struct {
	grest.NullInt64
}

NullInt64 is nullable Int64, it embeds a grest.NullInt64, so you can add your own method or override grest.NullInt64 method

func NewNullInt64

func NewNullInt64(val int64) NullInt64

NewNullInt64 return NullInt64

type NullJSON

type NullJSON struct {
	grest.NullJSON
}

NullJSON is nullable JSON, it embeds a grest.NullJSON, so you can add your own method or override grest.NullJSON method

type NullString

type NullString struct {
	grest.NullString
}

NullString is nullable String, it embeds a grest.NullString, so you can add your own method or override grest.NullString method

func NewNullString

func NewNullString(val string) NullString

NewNullString return NullString

type NullText

type NullText struct {
	grest.NullText
}

NullText is nullable Text, it embeds a grest.NullText, so you can add your own method or override grest.NullText method

func NewNullText

func NewNullText(val string) NullText

NewNullText return NullText

type NullTime

type NullTime struct {
	grest.NullTime
}

NullTime is nullable Time, it embeds a grest.NullTime, so you can add your own method or override grest.NullTime method

func NewNullTime

func NewNullTime(val time.Time) NullTime

NewNullTime return NullTime

type NullUUID

type NullUUID struct {
	grest.NullUUID
}

NullUUID is nullable UUID, it embeds a grest.NullUUID, so you can add your own method or override grest.NullUUID method

func NewNullUUID

func NewNullUUID(val ...string) NullUUID

NewNullUUID return NullUUID

type NullUnixTime added in v0.0.12

type NullUnixTime struct {
	grest.NullUnixTime
}

NullUnixTime is nullable Unix DateTime, it embeds a grest.NullUnixTime, so you can add your own method or override grest.NullUnixTime method

func NewNullUnixTime added in v0.0.12

func NewNullUnixTime(val time.Time) NullUnixTime

NewNullUnixTime return NullUnixTime

type OpenAPIOperation

type OpenAPIOperation struct {
	grest.OpenAPIOperation
}

type OpenAPIOperationInterface

type OpenAPIOperationInterface interface {
	grest.OpenAPIOperationInterface
}

type ServerInterface

type ServerInterface interface {
	AddRoute(path, method string, handler fiber.Handler, operation OpenAPIOperationInterface)
	AddStaticRoute(path string, fsConfig filesystem.Config)
	AddOpenAPIDoc(path string, f embed.FS)
	AddMiddleware(handler fiber.Handler)
	Start() error
	Test(req *http.Request, msTimeout ...int) (resp *http.Response, err error)
}

func Server

func Server() ServerInterface

type Setting

type Setting struct {
	Key   string `gorm:"column:key;primaryKey"`
	Value string `gorm:"column:value"`
}

func (Setting) KeyField

func (Setting) KeyField() string

func (Setting) MigrationKey

func (Setting) MigrationKey() string

func (Setting) SeedKey

func (Setting) SeedKey() string

func (Setting) TableName

func (Setting) TableName() string

func (Setting) ValueField

func (Setting) ValueField() string

type TelegramInterface

type TelegramInterface interface {
	AddMessage(text string)
	AddAttachment(file *multipart.FileHeader)
	Send() error
}

func Telegram

func Telegram(message ...string) TelegramInterface

type TranslatorInterface

type TranslatorInterface interface {
	Trans(lang, key string, params ...map[string]string) string
}

func Translator

func Translator() TranslatorInterface

type ValidatorInterface

type ValidatorInterface interface {
	IsValid(val any, tag string) bool
	ValidateStruct(val any, lang string) error
}

func Validator

func Validator() ValidatorInterface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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