restify

package module
v0.0.0-...-66803ac Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2024 License: MIT Imports: 26 Imported by: 0

README

Restify

Restify is an application built for the EVO Framework that allows you to generate RESTful APIs on the fly without the need to write any code. These APIs can be used for various purposes, including data management, data entry processes, dashboards, or communication with third-party applications.

Features

  • No Code Required: Automatically generate RESTful APIs without writing a single line of code.
  • Data Management: Use the generated APIs for managing data in your applications.
  • Data Entry: Facilitate data entry processes through RESTful endpoints.
  • Dashboard Integration: Seamlessly integrate with dashboards for real-time data management.
  • Third-Party Communication: Use the APIs to interact with external services or applications.

Table of contents


Getting Started
Prerequisites

Before you begin, ensure you have the following installed:

Usage
  1. Import Restify into your EVO application:

    import (
        "github.com/getevo/evo/v2"
        "github.com/getevo/restify"
    )
    
    func main() {
        evo.Setup()
        evo.Register(restify.App{})
        evo.Run()
    }
    
  2. Add Restify support to your model:

    type User struct {
        UserID   int    `gorm:"primaryKey;autoIncrement"`
        UserName string `gorm:"column:username;index;size:255"`
        Name     string `gorm:"column:name;size:255"`
        restify.API     // this signature enables Restify
    }
    
  3. Register your model with Restify:

    func (App) Register() {
        db.UseModel(User{})
    }
    

Documentation

Index

Constants

View Source
const (
	ContainOperator = "contains"
	NotNullOperator = "notnull"
	IsNullOperator  = "isnull"
	InOperator      = "in"
)

ContainOperator represents the string value "contains" which is used as an operator for containment operations. Examples of containment operations could be checking if a string contains a specific substring or if an array contains a specific element. This constant is used to indicate the containment operator in code logic. NotNullOperator represents the string value "notnull" which is used as an operator for checking if a value is not null. This constant is used to indicate the not null operator in code logic. IsNullOperator represents the string value "isnull" which is used as an operator for checking if a value is null. This constant is used to indicate the is null operator in code logic. InOperator represents the string

View Source
const (
	MethodGET    Method = "GET"
	MethodPOST   Method = "POST"
	MethodPatch  Method = "PATCH"
	MethodPUT    Method = "PUT"
	MethodDELETE Method = "DELETE"

	PermissionsModelInfo     Permission = "VIEW+MODEL_INFO"
	PermissionCreate         Permission = "CREATE"
	PermissionUpdate         Permission = "UPDATE"
	PermissionBatchCreate    Permission = "BATCH+CREATE"
	PermissionBatchUpdate    Permission = "BATCH+UPDATE"
	PermissionDelete         Permission = "DELETE"
	PermissionBatchDelete    Permission = "BATCH+DELETE"
	PermissionViewGet        Permission = "VIEW+GET"
	PermissionViewAll        Permission = "VIEW+ALL"
	PermissionViewPagination Permission = "VIEW+PAGINATION"
	PermissionSet            Permission = "SET"
)

Variables

View Source
var ErrorColumnNotExist = NewError("column does not exists", 500)

ErrorColumnNotExist represents an error indicating that a column does not exist.

View Source
var ErrorHandlerNotFound = NewError("handler not found", 404)
View Source
var ErrorObjectNotExist = NewError("object does not exists", 404)

ErrorObjectNotExist represents an error indicating that the object does not exist.

View Source
var ErrorPermissionDenied = NewError("permission denied", 403)
View Source
var ErrorUnauthorized = NewError("unauthorized", 403)
View Source
var ErrorUnsafe = NewError("unsafe request", 400)
View Source
var Prefix = "/admin/rest"

Functions

func EnablePostman

func EnablePostman()

func ModelDataFaker

func ModelDataFaker(schema *schema.Schema) interface{}

func OnAfterCreate

func OnAfterCreate(fn func(obj any, c *Context) error)

func OnAfterDelete

func OnAfterDelete(fn func(obj any, c *Context) error)

func OnAfterGet

func OnAfterGet(fn func(obj any, c *Context) error)

func OnAfterSave

func OnAfterSave(fn func(obj any, c *Context) error)

func OnAfterUpdate

func OnAfterUpdate(fn func(obj any, c *Context) error)

func OnBeforeCreate

func OnBeforeCreate(fn func(obj any, c *Context) error)

func OnBeforeDelete

func OnBeforeDelete(fn func(obj any, c *Context) error)

func OnBeforeSave

func OnBeforeSave(fn func(obj any, c *Context) error)

func OnBeforeUpdate

func OnBeforeUpdate(fn func(obj any, c *Context) error)

func PrettyJson

func PrettyJson(v interface{}) string

func SetDefaultPermissionHandler

func SetDefaultPermissionHandler(handler func(permissions Permissions, context *Context) bool)

func SetPostmanAuthorization

func SetPostmanAuthorization(_type AuthType, _value ...string)

func SetPrefix

func SetPrefix(prefix string)

Types

type API

type API struct{}

API is a flag to enable restful API endpoints.

type App

type App struct{}

func (App) Name

func (app App) Name() string

func (App) Priority

func (app App) Priority() application.Priority

func (App) Register

func (app App) Register() error

func (App) Router

func (app App) Router() error

func (App) WhenReady

func (app App) WhenReady() error

type AuthType

type AuthType string
const (
	AuthTypeNone     AuthType = "none"
	AuthTypeBasic    AuthType = "basic"
	AuthTypeBearer   AuthType = "bearer"
	AuthTypeDigest   AuthType = "digest"
	AuthTypeEdgeGrid AuthType = "edgegrid"
	AuthTypeHawk     AuthType = "hawk"
	AuthTypeOAuth1   AuthType = "oauth1"
	AuthTypeOAuth2   AuthType = "oauth2"
	AuthTypeNTLM     AuthType = "ntlm"
	AuthTypeHeader   AuthType = "header"
)

type Condition

type Condition struct {
	Field string `json:"field"`
	Op    string `json:"op"`
	Value any    `json:"value"`
}

type Context

type Context struct {
	Request    *evo.Request
	Object     reflect.Value
	Sample     interface{}
	Action     *Endpoint
	Response   *Pagination
	Schema     *schema.Schema
	Conditions []Condition

	Code int
	// contains filtered or unexported fields
}

Context represents the context of an HTTP request. It contains information about the request, the object being processed, the sample data, the action to be performed, the response, and the schema.

func (*Context) AddValidationErrors

func (context *Context) AddValidationErrors(errs ...error)

func (*Context) ApplyFilters

func (context *Context) ApplyFilters(query *gorm.DB) (*gorm.DB, *Error)

ApplyFilters applies filters to the query based on the request parameters in the context. It modifies the

func (*Context) CreateIndirectObject

func (context *Context) CreateIndirectObject() reflect.Value

CreateIndirectObject is a method of the Context type that returns a new indirect reflect.Value of the context Object's type.

func (*Context) CreateIndirectSlice

func (context *Context) CreateIndirectSlice() reflect.Value

CreateIndirectSlice returns a new indirect reflect value of a slice of the type of the Object field in the Context.

func (*Context) Error

func (context *Context) Error(err error, code int) *Error

func (*Context) FindByPrimaryKey

func (context *Context) FindByPrimaryKey(input interface{}) (bool, *Error)

FindByPrimaryKey is a method that searches for a record in the database based on the primary key values provided. The method takes an input parameter, which can be a struct or a

func (*Context) GetDBO

func (context *Context) GetDBO() *gorm.DB

func (*Context) HandleError

func (context *Context) HandleError(error *Error)

HandleError is a method of the Context type that sets the error message in the Response field and marks the Response as unsuccessful. It takes an error parameter.

func (*Context) Override

func (context *Context) Override(value any)

func (*Context) PrepareResponse

func (context *Context) PrepareResponse() *Pagination

PrepareResponse is a method of the Context type. It returns the response object of the context. If the response is not successful (success flag is false), it sets the data, size, page, total, total pages, and offset fields of the response to 0. It then returns the response object.

func (*Context) RestPermission

func (context *Context) RestPermission(permission Permission, object reflect.Value) bool

func (*Context) SetCondition

func (context *Context) SetCondition(condition string, op string, value any)

func (*Context) SetResponse

func (context *Context) SetResponse(response interface{})

SetResponse is a method of the Context type that sets the response data. It takes a response interface{} as a parameter and marshals it to JSON. If the response is nil, it returns immediately. If the response is not a slice, it marshals it as a single element slice. Otherwise, it marshals the response as is. If there is an error during marshaling, it returns immediately without setting the response. Note: The response is set to the `context.Request` using the `JSON` method.

func (*Context) Validate

func (context *Context) Validate(ptr any) error

func (*Context) ValidateNonZeroFields

func (context *Context) ValidateNonZeroFields(ptr any) error

type Controller

type Controller struct{}

Controller represents a controller type.

func (Controller) ModelsHandler

func (c Controller) ModelsHandler(request *evo.Request) interface{}

ModelsHandler returns all registered models.

func (Controller) PostmanHandler

func (c Controller) PostmanHandler(request *evo.Request) any

type Dictionary

type Dictionary[T any] []KeyValue[T]

Dictionary represents a collection of key-value pairs with a generic value type.

func (*Dictionary[T]) ContainsValue

func (d *Dictionary[T]) ContainsValue(v T) (bool, KeyValue[T])

ContainsValue checks if a value exists in the dictionary and returns the KeyValue if found.

func (*Dictionary[T]) Delete

func (d *Dictionary[T]) Delete(key string) error

Delete removes a key (and its associated value) from the dictionary.

func (*Dictionary[T]) Has

func (d *Dictionary[T]) Has(key string) bool

Has checks if a key exists in the dictionary.

func (*Dictionary[T]) Set

func (d *Dictionary[T]) Set(key string, v T)

Set sets a key to a value in the dictionary, updating if it already exists.

type DisableCreate

type DisableCreate struct{}

DisableCreate is a flag to disable the creation of new objects.

type DisableDelete

type DisableDelete struct{}

DisableDelete is a flag to disable the deletion of existing objects

type DisableList

type DisableList struct{}

DisableList is a flag to disable listing objects.

type DisableSet

type DisableSet struct{}

DisableSet is a flag to disable set endpoint

type DisableUpdate

type DisableUpdate struct{}

DisableUpdate is a flag to disable update of existing objects.

type Endpoint

type Endpoint struct {
	Name              string                        `json:"name"`
	Label             string                        `json:"-"`
	Method            Method                        `json:"method"`
	URL               string                        `json:"-"`
	PKUrl             bool                          `json:"pk_url"`
	AbsoluteURI       string                        `json:"url"`
	Description       string                        `json:"description"`
	Handler           func(context *Context) *Error `json:"-"`
	Resource          *Resource                     `json:"-"`
	URLParams         []Filter                      `json:"-"`
	Batch             bool                          `json:"batch"`
	AcceptData        bool                          `json:"accept_data"`
	Filterable        bool                          `json:"filterable"`
	Pagination        bool                          `json:"pagination"`
	PostmanCollection postman.Collection            `json:"-"`
}

func (*Endpoint) GenerateDescription

func (action *Endpoint) GenerateDescription() string

func (*Endpoint) RegisterRouter

func (action *Endpoint) RegisterRouter()

type Error

type Error struct {
	Code    int
	Message string
}

func NewError

func NewError(message string, code int) Error

type Feature

type Feature struct {
	DisableCreate bool
	DisableUpdate bool
	DisableList   bool
	DisableDelete bool
	DisableSet    bool
	API           bool
}

Feature struct represents a set of features that can be enabled or disabled. Each feature has a corresponding boolean field that indicates whether it is enabled or disabled.

func GetFeatures

func GetFeatures(v interface{}) Feature

type Field

type Field struct {
	Name      string `json:"label"`
	FieldName string `json:"-"`
	DBName    string `json:"name,omitempty"`
	Type      string `json:"type,omitempty"`
	Default   string `json:"default,omitempty"`
	PK        bool   `json:"pk,omitempty"`
}

Field represents a field in a data structure. It contains metadata about the field, such as its name, database name, type, default value, and whether it is a primary key.

type Filter

type Filter struct {
	Title   string             `json:"title,omitempty"`
	Type    string             `json:"type,omitempty"`
	Options Dictionary[string] `json:"options,omitempty"`
	Name    string             `json:"name,omitempty"`
	Filter  string             `json:"-"`
}

Filter represents a filter for data retrieval. It contains the following properties:

- Title: the title of the filter. - Type: the type of the filter. - Options: dictionary of options for the filter. - Name: the name of the filter. - Filter: the filter condition to be applied.

type Handler

type Handler struct {
}

func (Handler) All

func (Handler) All(context *Context) *Error

All queries the database and retrieves all objects based on the given context. It applies filters, handles OnBefore and OnAfter events, and sets the response. It returns an error if any occurred during the process.

func (Handler) BatchCreate

func (Handler) BatchCreate(context *Context) *Error

func (Handler) BatchDelete

func (h Handler) BatchDelete(context *Context) *Error

BatchDelete delete multiple objects in the database

func (Handler) BatchUpdate

func (Handler) BatchUpdate(context *Context) *Error

func (Handler) Create

func (Handler) Create(context *Context) *Error

Create takes a Context as input and creates a new object. It uses the context's Request and DBO to perform the creation. The object to be created is retrieved from the context's Object field. The object is parsed from the request's body using the BodyParser method. The object can optionally implement the OnBeforeCreate method, which is called OnBefore the creation. The object can optionally implement the ValidateCreate method, which is called to validate the object OnBefore creation. The object is then created in the database using the DBO's Create method. If the object implements the OnAfterCreate method, it is called OnAfter the creation. The created object is set as the data in the context's Response field. Returns an error if any error occurs during the creation process.

func (Handler) Delete

func (Handler) Delete(context *Context) *Error

Delete deletes an object from the database. It takes a Context pointer as a parameter. It returns an error if an error occurs during the deletion process.

func (Handler) Get

func (Handler) Get(context *Context) *Error

Get is a function that retrieves an object from the context. It performs pre- and post-get operations on the object if they are implemented. It finds the object by its primary key, sets it as the response data in the context, and returns nil if successful. If the object does not exist, it returns an error of type ErrorObjectNotExist. It returns an error if any operation fails.

func (Handler) ModelInfo

func (Handler) ModelInfo(context *Context) *Error

func (Handler) Paginate

func (Handler) Paginate(context *Context) *Error

Paginate applies pagination to a database query based on the context provided. It modifies the context's response object with the paginated data.

func (Handler) Set

func (h Handler) Set(context *Context) *Error

Set updates the collection by creating new items that don't already exist and removing any items that are not present in the provided list.

func (Handler) Update

func (Handler) Update(context *Context) *Error

Update updates an object in the database based on the provided context. It retrieves the database object, checks if it exists in the database, parses the request body to update the object, and executes the updates on the database. It also calls the OnBeforeUpdate and ValidateUpdate methods if they are implemented by the object to perform any necessary operations OnBefore and OnAfter the update. Finally, it sets the updated object as the response data in the context.

type Info

type Info struct {
	Name      string      `json:"name,omitempty"`
	ID        string      `json:"id,omitempty"`
	Fields    []Field     `json:"fields,omitempty"`
	Endpoints []*Endpoint `json:"endpoints,omitempty"`
}

Info represents a structured information object.

It contains the following fields: - Name: The name of the object - ID: The ID of the object - Fields: An array of Field objects that represent the fields of the object - Endpoints: An array of Endpoint objects that represent the endpoints associated with the object.

type KeyValue

type KeyValue[T any] struct {
	Key   string `json:"key,omitempty"`
	Value T      `json:"value,omitempty"`
}

KeyValue represents a key-value pair with a generic value type.

type Method

type Method string

type Pagination

type Pagination struct {
	Records         int               `json:"records,omitempty"`    // Total rows
	Pages           int               `json:"pages,omitempty"`      // total number of pages
	Limit           int               `json:"limit,omitempty"`      // number of rows per page
	First           int               `json:"first,omitempty"`      // First Page
	Last            int               `json:"last,omitempty"`       // Last Page
	PageRange       []int             `json:"page_range,omitempty"` // Range of visible pages
	Data            interface{}       `json:"data,omitempty"`
	Total           int64             `json:"total"`
	Offset          int               `json:"offset"`
	TotalPages      int               `json:"total_pages"`
	Page            int               `json:"current_page"`
	Size            int               `json:"size"`
	Success         bool              `json:"success"`
	Error           string            `json:"error"`
	Type            string            `json:"type"`
	ValidationError []ValidationError `json:"validation_error"`
}

Pagination represents a utility type for handling pagination in Go.

Fields: - Records: Total number of rows. - CurrentPage: Current page loaded. - Pages: Total number of pages. - Limit: Number of rows per page. - First: First page. - Last: Last page. - PageRange: Range of visible pages.

Methods: - SetCurrentPage: Sets the current page based on the provided value. If the value is 0, the current page is set to 1. - SetLimit: Sets the limit of rows per page. If the value is 0, the limit is set to the minimum limit of 10. If the limit is less than the minimum limit, it is set to the minimum

func (*Pagination) Create

func (p *Pagination) Create(model *gorm.DB, i interface{}, request *evo.Request) error

func (*Pagination) GetOffset

func (p *Pagination) GetOffset() int

GetOffset calculates the offset for paginating the data based on the current page and limit

func (*Pagination) GetPage

func (p *Pagination) GetPage() int

GetPage returns the current page of the pagination struct

func (*Pagination) SetCurrentPage

func (p *Pagination) SetCurrentPage(page int)

SetCurrentPage sets the value of CurrentPage in the Pagination struct. If the input page is not equal to zero, p.CurrentPage will be set to the input page. Otherwise, p.CurrentPage will be set to 1.

func (*Pagination) SetLast

func (p *Pagination) SetLast()

SetLast sets the value of the Last page in the pagination struct. It calculates the value by adding the current offset to the limit. If the calculated value is greater than the total number of records, it sets the Last page to the total number of records.

func (*Pagination) SetLimit

func (p *Pagination) SetLimit(limit int)

SetLimit sets the limit per page for the pagination struct. The limit must be between 10 and 100 (inclusive). If the limit is 0, it will be set to 10. If the limit is less than 10

func (*Pagination) SetPageRange

func (p *Pagination) SetPageRange()

SetPageRange sets the value of PageRange in the Pagination struct. It determines the range of visible pages based on the current page and the total number of pages.

func (*Pagination) SetPages

func (p *Pagination) SetPages()

SetPages sets the total number of pages in the pagination struct based on the number of records and the limit per page. If the number of records is 0, it sets the number of pages to 1. If there is no remainder when dividing the number of records by the limit, it sets the number of pages to the integer division. Otherwise, it sets the number of pages to the integer division plus 1. If the number of pages is 0, it sets it to 1. After setting the number of pages, it calls the SetLast and SetPageRange methods to update the last page indicator and the range of visible pages respectively.

type Permission

type Permission string

func (Permission) ToPermissions

func (p Permission) ToPermissions() Permissions

type Permissions

type Permissions []string

func (Permissions) Has

func (p Permissions) Has(perms ...string) bool

type Resource

type Resource struct {
	Instance            any            `json:"-"`
	PrimaryFieldDBNames []string       `json:"primary_key"`
	Actions             []*Endpoint    `json:"actions"`
	Schema              *schema.Schema `json:"-"`
	Type                reflect.Type   `json:"-"`
	Ref                 reflect.Value  `json:"-"`
	Table               string         `json:"table"`
	Path                string         `json:"path"`
	Name                string         `json:"model"`
	Feature             Feature        `json:"feature"`
	PostmanGroup        *postman.Item  `json:"-"`
}

Resource represents a resource in an API. It holds information about the object, actions, path, schema, table, name, model, JavaScript model, and parameters of the resource.

func UseModel

func UseModel(model any) *Resource

func (*Resource) SetAction

func (res *Resource) SetAction(action *Endpoint)

type ValidationError

type ValidationError struct {
	Field string `json:"field"`
	Error string `json:"error"`
}

Jump to

Keyboard shortcuts

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