jargo

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2018 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MsgConnectionTimeout is sent to the client
	// if they don't send a connection message
	// before Realtime.ConnectionMessageTimeout is exceeded.
	MsgConnectionTimeout = "CONNECTION_TIMEOUT"

	// MsgConnectionDisallowed is sent to the client
	// if Realtime.HandleConnection returns false.
	MsgConnectionDisallowed = "CONNECTION_DISALLOWED"

	MsgOk              = `{"status":"ok"}`
	MsgInvalidResource = `{"error":"INVALID_RESOURCE"}`
	MsgAccessDenied    = `{"error":"ACCESS_DENIED"}`
)
View Source
const DefaultMaxPageSize = 25

DefaultMaxPageSize is the default maximum number of allowed entries per page.

Variables

View Source
var ErrForbidden = NewApiError(
	http.StatusForbidden,
	"FORBIDDEN",
	"forbidden",
)
View Source
var ErrInternalServerError = NewApiError(
	http.StatusInternalServerError,
	"INTERNAL_SERVER_ERROR",
	"internal server error",
)

ErrInternalServerError is an ApiError indicating an unspecified internal error.

View Source
var ErrInvalidId = NewApiError(
	http.StatusBadRequest,
	"INVALID_ID",
	"invalid id parameter",
)
View Source
var ErrNotAcceptable = NewApiError(
	http.StatusNotAcceptable,
	"NOT_ACCEPTABLE",
	fmt.Sprintf("accept header must contain %s without any media type parameters", jsonapi.MediaType),
)
View Source
var ErrNotFound = NewApiError(
	http.StatusNotFound,
	"RESOURCE_NOT_FOUND",
	"resource not found",
)
View Source
var ErrUnsupportedMediaType = NewApiError(
	http.StatusUnsupportedMediaType,
	"UNSUPPORTED_MEDIA_TYPE",
	fmt.Sprintf("media type must be %s", jsonapi.MediaType),
)

Functions

func ParseCreatePayload

func ParseCreatePayload(c *Context, req *CreateRequest) (interface{}, error)

func ParseFieldParameters

func ParseFieldParameters(query map[string][]string) map[string][]string

func ParseFilterParameters

func ParseFilterParameters(query map[string][]string) map[string]map[string][]string

func ParsePageParameters

func ParsePageParameters(query map[string][]string) map[string]string

func ParseResourceId

func ParseResourceId(idStr string) (int64, error)

func ParseSortParameters

func ParseSortParameters(query map[string][]string) map[string]bool

func ParseUpdatePayload

func ParseUpdatePayload(c *Context, req *UpdateRequest) (interface{}, error)

Types

type ApiError

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

An ApiError is a struct containing information about an error that occurred handling a request. ApiError implements error and Response, so it can be returned both as error value in functions and as Response value in HandlerFuncs.

func ErrInvalidPayload

func ErrInvalidPayload(detail string) *ApiError

func ErrInvalidQueryParams

func ErrInvalidQueryParams(detail string) *ApiError

func ErrUnauthorized

func ErrUnauthorized(detail string) *ApiError

func ErrValidationFailed

func ErrValidationFailed(errors validator.ValidationErrors) *ApiError

func NewApiError

func NewApiError(status int, code string, detail string) *ApiError

NewApiError returns a new ApiError from a status code, error code and error detail string.

func NewErrorResponse

func NewErrorResponse(err error) *ApiError

NewErrorResponse returns a Response containing an error payload according to the JSON API spec. See http://jsonapi.org/format/#errors

If the underlying error is an instance of ApiError, the error itself is returned. Otherwise, it logs the error as an internal server error and returns ErrInternalServerError.

func (*ApiError) Error

func (e *ApiError) Error() string

Error satisfies the error interface.

func (*ApiError) Payload

func (e *ApiError) Payload() (string, error)

Payload satisfies the Response interface.

func (*ApiError) Response

func (e *ApiError) Response() (int, string)

Body satisfies the ferry.Response interface.

func (*ApiError) Status

func (e *ApiError) Status() int

Status satisfies the Response interface.

func (*ApiError) ToErrorObject

func (e *ApiError) ToErrorObject() *jsonapi.ErrorObject

ToErrorObject converts the ApiError to a jsonapi.ErrorObject.

type Application

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

Application is the central component of jargo.

func NewApplication

func NewApplication(db *pg.DB) *Application

NewApplication returns a new Application using the given pg handle and a default Validate instance.

func NewApplicationWithValidate

func NewApplicationWithValidate(db *pg.DB, validate *validator.Validate) *Application

NewApplicationWithErrorHandler returns a new Application using the given pg handle and Validate instance.

func (*Application) AddController

func (app *Application) AddController(c *Controller)

AddController registers a Controller with the Application.

func (*Application) Bridge

func (app *Application) Bridge(f *ferry.Ferry, namespace string)

Bridge registers all of the application's controller's actions with a Ferry instance.

func (*Application) BridgeRoot

func (app *Application) BridgeRoot(f *ferry.Ferry)

BridgeRoot registers all of the application's controller's actions with a Ferry instance at root level.

func (*Application) DB

func (app *Application) DB() *pg.DB

DB returns the pg database handle used by the Application.

func (*Application) MaxPageSize

func (app *Application) MaxPageSize() int

MaxPageSize returns the maximum number of allowed entries per page for paginated results.

func (*Application) MustRegisterResource

func (app *Application) MustRegisterResource(model interface{}) *Resource

MustRegisterResource calls RegisterResource and panics if it encounters an error.

func (*Application) RegisterResource

func (app *Application) RegisterResource(model interface{}) (*Resource, error)

RegisterResource registers and initializes a Resource and all related Resources. If the Resource has already been registered, its cached value is returned.

Panics if model is not an instance of a properly annotated Resource Model.

func (*Application) SetMaxPageSize

func (app *Application) SetMaxPageSize(maxPageSize int)

SetMaxPageSize sets the maximum number of allowed entries per page. Panics if value is not positive.

func (*Application) Validate

func (app *Application) Validate() *validator.Validate

Validate returns the Validate instance used to validate create and update requests.

type Context

type Context struct {
	*ferry.Context
	// contains filtered or unexported fields
}

func (*Context) Application

func (c *Context) Application() *Application

func (*Context) DB

func (c *Context) DB() *pg.DB

func (*Context) Resource

func (c *Context) Resource() *Resource

type Controller

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

A Controller is responsible for all Actions related to a specific Resource.

func NewCRUDController

func NewCRUDController(resource *Resource) *Controller

NewCRUDController returns a new Controller for a Resource with the default JSON API-compliant Index, Show, Create, Update and Delete Actions.

func NewController

func NewController(resource *Resource) *Controller

NewController returns a new Controller for a Resource.

func (*Controller) SetAction

func (c *Controller) SetAction(method string, path string, handlers ...HandlerFunc)

func (*Controller) SetCreateAction

func (c *Controller) SetCreateAction(handlers ...CreateHandlerFunc)

SetCreateAction sets the Controller's Create Action.

func (*Controller) SetDeleteAction

func (c *Controller) SetDeleteAction(handlers ...DeleteHandlerFunc)

SetDeleteAction sets the Controller's Delete Action.

func (*Controller) SetIndexAction

func (c *Controller) SetIndexAction(handlers ...IndexHandlerFunc)

SetIndexAction sets the Controller's Index Action.

func (*Controller) SetShowAction

func (c *Controller) SetShowAction(handlers ...ShowHandlerFunc)

SetShowAction sets the Controller's Show Action.

func (*Controller) SetUpdateAction

func (c *Controller) SetUpdateAction(handlers ...UpdateHandlerFunc)

SetUpdateAction sets the Controller's Update Action.

func (*Controller) Use

func (c *Controller) Use(middleware ...HandlerFunc)

Use adds handler functions to be run before the Controller's action handlers.

type CreateHandlerFunc

type CreateHandlerFunc func(context *Context, request *CreateRequest) Response

A CreateHandlerFunc is a function handling a create request.

type CreateRequest

type CreateRequest struct {
	Fields  *FieldSet
	Payload io.Reader
}

func ParseCreateRequest

func ParseCreateRequest(c *Context) (*CreateRequest, error)

type DeleteHandlerFunc

type DeleteHandlerFunc func(context *Context, request *DeleteRequest) Response

A DeleteHandlerFunc is a function handling a delete request.

type DeleteRequest

type DeleteRequest struct {
	ResourceId int64
}

func ParseDeleteRequest

func ParseDeleteRequest(c *Context) (*DeleteRequest, error)

type FieldSet

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

type Filter

type Filter struct {
	Eq   []string
	Not  []string
	Like []string
	Lt   []string
	Lte  []string
	Gt   []string
	Gte  []string
}

A Filter contains values to be filtered by, each of the filter operators being connected via a logical OR, and all of the values for an operator being connected via a logical AND.

type Filters

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

type HandleConnectionFunc

type HandleConnectionFunc func(socket *glue.Socket, message string) bool

type HandlerFunc

type HandlerFunc func(context *Context) Response

A HandlerFunc is a function handling a generic jargo request.

type IndexHandlerFunc

type IndexHandlerFunc func(context *Context, request *IndexRequest) Response

An IndexHandlerFunc is a function handling an index request.

type IndexRequest

type IndexRequest struct {
	Fields     *FieldSet
	Filters    *Filters
	SortFields *SortFields
	Pagination *Pagination
}

func ParseIndexRequest

func ParseIndexRequest(c *Context) (*IndexRequest, error)

type MaySubscribeFunc

type MaySubscribeFunc func(socket *glue.Socket, resource *Resource, id int64) bool

type Pagination

type Pagination struct {
	Number int // page[number]
	Size   int // page[size]
}

func ParsePagination

func ParsePagination(values map[string]string, maxPageSize int) (*Pagination, error)

type Query

type Query struct {
	*orm.Query
	// contains filtered or unexported fields
}

A Query is used to communicate with the database. It implements Response so it can be returned from handler functions and executed upon sending.

func (*Query) Execute

func (q *Query) Execute() (interface{}, error)

Execute executes the query and returns the resulting resource model instance.

func (*Query) Fields

func (q *Query) Fields(fs *FieldSet) *Query

Fields sets a FieldSet instance to apply on Query execution. FieldSets are also applied to JSON API payloads created in the Send method.

func (*Query) Filters

func (q *Query) Filters(f *Filters) *Query

Filters sets a Filters instance to apply on Query execution.

Panics if Query is not a Select Query.

func (*Query) Pagination

func (q *Query) Pagination(p *Pagination) *Query

Pagination sets a Pagination instance to apply on Query execution.

Panics if Query is not a Select many Query.

func (*Query) Payload

func (q *Query) Payload() (string, error)

Payload satisfies Response

func (*Query) Response

func (q *Query) Response() Response

Response returns the Response for the query's execution result. Executes the query if it hasn't been executed yet.

func (*Query) Result

func (q *Query) Result() (interface{}, error)

Result returns the query result resource model. Executes the query if it hasn't been executed yet.

func (*Query) Sort

func (q *Query) Sort(s *SortFields) *Query

Sort sets a SortFields instance to apply on Query execution.

Panics if Query is not a Select many Query.

func (*Query) Status

func (q *Query) Status() int

Status satisfies Response

type Realtime

type Realtime struct {
	*glue.Server

	// ConnectionMessageTimeout is the time
	// to wait for the connection message.
	// Defaults to 10s.
	ConnectionMessageTimeout time.Duration

	// HandleConnection is is the HandleConnectionFunc
	// to be invoked when a new socket connection
	// has sent their connection message.
	// If it returns true, the connection is allowed, otherwise
	// it is immediately closed.
	// Defaults to a function always returning true.
	HandleConnection HandleConnectionFunc

	MaySubscribe MaySubscribeFunc
	// contains filtered or unexported fields
}

A Realtime instance allows clients to subscribe to resource instances via websocket.

func NewRealtime

func NewRealtime(app *Application, namespace string) *Realtime

NewRealtime returns a new Realtime instance for an Application and namespace using the default HandleConnection and MaySubscribe handlers, which allow all connections and subscriptions.

func (*Realtime) Run

func (r *Realtime) Run() error

Run starts the Realtime server and listens for incoming socket connections. This is a blocking method.

type Resource

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

implements api.Resource

func (*Resource) Delete

func (r *Resource) Delete(db orm.DB) *Query

Delete returns a new Delete Query.

func (*Resource) DeleteById

func (r *Resource) DeleteById(db orm.DB, id int64) *Query

DeleteById returns a new Delete Query deleting the Resource Instance with the given id.

func (*Resource) DeleteInstance

func (r *Resource) DeleteInstance(db orm.DB, instance interface{}) *Query

DeleteInstance returns a new Delete Query deleting the Resource Instance provided (by id field).

Panics if instance is not a Resource Model Instance.

func (*Resource) Filters

func (r *Resource) Filters(filters map[string]*Filter) (*Filters, error)

Filters returns a Filters instance for a map of JSON API field names and Filter instances.

Returns an error if a field is not a valid JSON API field name for this resource or a filter operator is not supported.

func (*Resource) IdFilter

func (r *Resource) IdFilter(id int64) *Filters

IdFilter returns a Filters instance filtering by the id field

func (*Resource) Initialize

func (r *Resource) Initialize(db *pg.DB) error

Initialize makes the Resource ready to use, creating the necessary database tables. If it has already been initialized, it is not initialized again.

func (*Resource) InsertCollection

func (r *Resource) InsertCollection(db orm.DB, instances []interface{}) *Query

InsertCollection returns a new Insert Many Query inserting the Resource Model Collection provided.

Panics if instances is not a Slice of Resource Model Instances.

func (*Resource) InsertInstance

func (r *Resource) InsertInstance(db orm.DB, instance interface{}) *Query

InsertInstance returns a new Insert One Query inserting the Resource Model Instance provided.

Panics if instance is not a Resource Model Instance.

func (*Resource) JSONAPIName

func (r *Resource) JSONAPIName() string

JSONAPIName returns the JSON API member name of the Resource.

func (*Resource) ParseFieldSet

func (r *Resource) ParseFieldSet(parsed map[string][]string) (*FieldSet, error)

ParseFieldSet returns a FieldSet for this Resource from a map of field parameters.

Returns ErrInvalidQueryParams when encountering invalid query values.

func (*Resource) ParseFilters

func (r *Resource) ParseFilters(parsed map[string]map[string][]string) (*Filters, error)

ParseFilters parses filter query parameters according to JSON API spec, returning the resulting Filters for this Resource. http://jsonapi.org/format/#fetching-filtering

Returns ErrInvalidQueryParams when encountering invalid query values.

func (*Resource) ParseJsonapiPayload

func (r *Resource) ParseJsonapiPayload(in io.Reader, validate *validator.Validate) (interface{}, error)

ParseJsonapiPayload parses a payload from a reader into a Resource Model Instance according to the JSON API spec. If validate is not nil, it is used to validate all writable fields. Returns a new Resource Model Instance.

func (*Resource) ParseJsonapiPayloadString

func (r *Resource) ParseJsonapiPayloadString(payload string, validate *validator.Validate) (interface{}, error)

ParseJsonapiPayloadString parses a payload string into a Resource Model Instance according to the JSON API spec. If validate is not nil, it is used to validate all writable fields. Returns a new Resource Model Instance.

func (*Resource) ParseJsonapiUpdatePayload

func (r *Resource) ParseJsonapiUpdatePayload(in io.Reader, instance interface{}, validate *validator.Validate) (interface{}, error)

ParseJsonapiUpdatePayload parses a payload from a reader into a Resource Model Instance according to the JSON API spec, applying it to an existing Resource Model Instance. If validate is not nil, it is used to validate all writable fields. Returns a new Resource Model Instance.

func (*Resource) ParseJsonapiUpdatePayloadString

func (r *Resource) ParseJsonapiUpdatePayloadString(payload string, instance interface{}, validate *validator.Validate) (interface{}, error)

ParseJsonapiUpdatePayloadString parses a payload string into a Resource Model Instance according to the JSON API spec, applying it to an existing Resource Model Instance. If validate is not nil, it is used to validate all writable fields. Returns a new Resource Model Instance.

func (*Resource) ParseSortFields

func (r *Resource) ParseSortFields(sort map[string]bool) (*SortFields, error)

SortFields returns a SortField instance for a map of JSON API fields names and sort direction (true being ascending).

Returns an error if a field is not a valid JSON API field name for this resource.

func (*Resource) Response

func (r *Resource) Response(data interface{}, fieldSet *FieldSet) Response

Response returns a Response that sends a Resource Model Instance according to JSON API spec, using the FieldSet provided.

Panics if data is not a Resource Model Instance or Slice of Resource Model Instances.

func (*Resource) ResponseAllFields

func (r *Resource) ResponseAllFields(data interface{}) Response

ResponseAllFields returns a Response sending a Resource Model Instance according to JSON API spec, including all model fields.

Panics if data is not a Resource Model Instance or Slice of Resource Model Instances.

func (*Resource) ResponseWithStatusCode

func (r *Resource) ResponseWithStatusCode(data interface{}, fieldSet *FieldSet, status int) Response

ResponseWithStatusCode returns a Response sending a Resource Model Instance according to JSON API spec, setting the status code and using the FieldSet provided.

Panics if data is not a Resource Model Instance or Slice of Resource Model Instances.

func (*Resource) Select

func (r *Resource) Select(db orm.DB) *Query

Select returns a new Select Many Query.

func (*Resource) SelectById

func (r *Resource) SelectById(db orm.DB, id int64) *Query

Select returns a new Select One Query selecting the Resource Instance with the given id.

func (*Resource) SelectOne

func (r *Resource) SelectOne(db orm.DB) *Query

Select returns a new Select One Query.

func (*Resource) SortById

func (r *Resource) SortById() *SortFields

SortById returns a SortFields instance sorting by the id field in descending order.

func (*Resource) UpdateCollection

func (r *Resource) UpdateCollection(db orm.DB, instances []interface{}) *Query

Update returns a new Update Many Query updating the values of the Resource Model Collection provided.

Panics if instances is not a Slice of Resource Model Instances.

func (*Resource) UpdateInstance

func (r *Resource) UpdateInstance(db orm.DB, instance interface{}) *Query

Update returns a new Update Query updating the values of the Resource Model Instance provided.

Panics if instance is not a Resource Model Instance.

func (*Resource) Validate

func (r *Resource) Validate(validate *validator.Validate, instance interface{}) error

Validate validates a Resource Model Instance according to the Resource validation rules, using the Validate instance provided.

type Response

type Response interface {
	// Status returns the HTTP Status
	// for the response.
	Status() int
	// Payload returns the JSON API payload
	// to send to the client.
	Payload() (string, error)
}

func DefaultCreateResourceHandler

func DefaultCreateResourceHandler(c *Context, req *CreateRequest) Response

DefaultCreateResourceHandler is the HandlerFunc used by the builtin JSON API Create Action. It supports Sparse Fieldsets according to the JSON API spec. http://jsonapi.org/format/#crud-creating

func DefaultDeleteResourceHandler

func DefaultDeleteResourceHandler(c *Context, req *DeleteRequest) Response

DefaultDeleteResourceHandler is the HandlerFunc used by the builtin JSON API Delete Action. http://jsonapi.org/format/#crud-deleting

func DefaultIndexResourceHandler

func DefaultIndexResourceHandler(c *Context, req *IndexRequest) Response

DefaultIndexResourceHandler is the HandlerFunc used by the builtin JSON API Index Action. It supports Pagination, Sorting, Filtering and Sparse Fieldsets according to the JSON API spec. http://jsonapi.org/format/#fetching

func DefaultShowResourceHandler

func DefaultShowResourceHandler(c *Context, req *ShowRequest) Response

DefaultShowResourceHandler is the HandlerFunc used by the builtin JSON API Show Action. It supports Sparse Fieldsets according to the JSON API spec. http://jsonapi.org/format/#fetching

func DefaultUpdateResourceHandler

func DefaultUpdateResourceHandler(c *Context, req *UpdateRequest) Response

DefaultUpdateResourceHandler is the HandlerFunc used by the builtin JSON API Update Action. It supports Sparse Fieldsets according to the JSON API spec. http://jsonapi.org/format/#crud-updating

func NewResponse

func NewResponse(status int, payload string) Response

type ShowHandlerFunc

type ShowHandlerFunc func(context *Context, request *ShowRequest) Response

A ShowHandlerFunc is a function handling a show request.

type ShowRequest

type ShowRequest struct {
	Fields     *FieldSet
	ResourceId int64
}

func ParseShowRequest

func ParseShowRequest(c *Context) (*ShowRequest, error)

type SortFields

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

type UpdateHandlerFunc

type UpdateHandlerFunc func(context *Context, request *UpdateRequest) Response

An UpdateHandlerFunc is a function handling an update request.

type UpdateRequest

type UpdateRequest struct {
	Fields     *FieldSet
	ResourceId int64
	Payload    io.Reader
}

func ParseUpdateRequest

func ParseUpdateRequest(c *Context) (*UpdateRequest, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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