jargo

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2018 License: MIT Imports: 24 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 NormalizeNamespace added in v0.0.2

func NormalizeNamespace(namespace string) string

NormalizeNamespace ensures that the namespace starts and ends with a slash.

func ParseCreatePayload

func ParseCreatePayload(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(req *UpdateRequest) (interface{}, error)

func ResponseToFerry added in v0.0.2

func ResponseToFerry(res Response) ferry.Response

ResponseToFerry creates a ferry.Response from a Response, invoking its Payload() method and handling any errors.

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(options Options) *Application

NewApplication returns a new Application for the given Options.

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

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

MustRegisterResource calls RegisterResource and panics if it encounters an error.

func (*Application) NewCRUDController added in v0.0.2

func (app *Application) 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. If the Application already has a controller for this resource, it is replaced with the newly created controller.

func (*Application) NewController added in v0.0.2

func (app *Application) NewController(resource *Resource) *Controller

NewController creates a new controller for a given resource. If the Application already has a controller for this resource, it is replaced with the newly created controller.

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) ServeHTTP added in v0.0.2

func (app *Application) ServeHTTP(addr string, namespace string) error

ServeHTTP serves the Application via HTTP under the given namespace. This is a blocking method.

func (*Application) ToFerry added in v0.0.2

func (app *Application) ToFerry(namespace string) *ferry.Ferry

ToFerry creates a new Ferry instance hosting the Application under the given namespace.

func (*Application) Validate

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

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

type Controller

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

A Controller is responsible for all Actions related to a specific 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(req *CreateRequest) Response

A CreateHandlerFunc is a function handling a create request.

type CreateRequest

type CreateRequest struct {
	*Request
	// contains filtered or unexported fields
}

func ParseCreateRequest

func ParseCreateRequest(base *Request) (*CreateRequest, error)

func (*CreateRequest) Fields

func (r *CreateRequest) Fields() *FieldSet

type DeleteHandlerFunc

type DeleteHandlerFunc func(req *DeleteRequest) Response

A DeleteHandlerFunc is a function handling a delete request.

type DeleteRequest

type DeleteRequest struct {
	*Request
	// contains filtered or unexported fields
}

func ParseDeleteRequest

func ParseDeleteRequest(base *Request) (*DeleteRequest, error)

func (*DeleteRequest) ResourceId

func (r *DeleteRequest) ResourceId() int64

type FieldSet

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

func (*FieldSet) FieldNames added in v0.0.2

func (fs *FieldSet) FieldNames() []string

FieldNames returns the JSON API Member names of the FieldSet's fields.

func (*FieldSet) Without added in v0.0.2

func (fs *FieldSet) Without(names ...string) *FieldSet

Without returns a copy of the FieldSet instance not containing fields with the JSON API Member names passed.

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(req *Request) Response

A HandlerFunc is a function handling a generic jargo request.

type IndexHandlerFunc

type IndexHandlerFunc func(req *IndexRequest) Response

An IndexHandlerFunc is a function handling an index request.

type IndexRequest

type IndexRequest struct {
	*Request
	// contains filtered or unexported fields
}

func ParseIndexRequest

func ParseIndexRequest(base *Request) (*IndexRequest, error)

func (*IndexRequest) Fields

func (r *IndexRequest) Fields() *FieldSet

func (*IndexRequest) Filters

func (r *IndexRequest) Filters() *Filters

func (*IndexRequest) Pagination

func (r *IndexRequest) Pagination() Pagination

type MaySubscribeFunc

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

type Options added in v0.0.2

type Options struct {
	// DB is required.
	DB *pg.DB

	PaginationStrategies *PaginationStrategies
	MaxPageSize          int

	Validate *validator.Validate
}

Options is used to configure an Application when creating it.

type Pagination

type Pagination interface {
	// contains filtered or unexported methods
}

Pagination is responsible for applying sorting and pagination settings to a Query.

type PaginationStrategies added in v0.0.2

type PaginationStrategies struct {
	// Offset determines whether
	// offset-based pagination is enabled.
	Offset bool

	// Cursor determines whether
	// cursor-based/keyset pagination is enabled
	Cursor bool
}

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) 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) Bridge added in v0.0.2

func (r *Realtime) Bridge(mux *http.ServeMux) error

Bridge registers the Realtime instance with a ServeMux. It prepares the Realtime instance for request handling by invoking Start.

func (*Realtime) Namespace added in v0.0.2

func (r *Realtime) Namespace() string

Namespace returns the namespace the realtime instance listens on.

func (*Realtime) Release added in v0.0.2

func (r *Realtime) Release()

Release stops all internal goroutines. Should be called after serving is done.

func (*Realtime) ServeHTTP added in v0.0.2

func (r *Realtime) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Realtime) SetNamespace added in v0.0.2

func (r *Realtime) SetNamespace(namespace string)

SetNamespace sets the namespace the realtime instance listens on. Panics if the realtime instance is running.

func (*Realtime) Start added in v0.0.2

func (r *Realtime) Start() error

Start prepares the Realtime instance to handle incoming requests. This must be called before registering the Realtime instance as an http handler.

After handling is done, Release should be called to stop all internal goroutines.

type Request added in v0.0.2

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

func (*Request) Application added in v0.0.2

func (r *Request) Application() *Application

func (*Request) DB added in v0.0.2

func (r *Request) DB() *pg.DB

func (*Request) Resource added in v0.0.2

func (r *Request) Resource() *Resource

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) ParsePagination added in v0.0.2

func (r *Resource) ParsePagination(app *Application, sortParams map[string]bool, pageParams map[string]string) (Pagination, error)

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) 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(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(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(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(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(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(req *ShowRequest) Response

A ShowHandlerFunc is a function handling a show request.

type ShowRequest

type ShowRequest struct {
	*Request
	// contains filtered or unexported fields
}

func ParseShowRequest

func ParseShowRequest(base *Request) (*ShowRequest, error)

func (*ShowRequest) Fields

func (r *ShowRequest) Fields() *FieldSet

func (*ShowRequest) ResourceId

func (r *ShowRequest) ResourceId() int64

type UpdateHandlerFunc

type UpdateHandlerFunc func(req *UpdateRequest) Response

An UpdateHandlerFunc is a function handling an update request.

type UpdateRequest

type UpdateRequest struct {
	*Request
	// contains filtered or unexported fields
}

func ParseUpdateRequest

func ParseUpdateRequest(base *Request) (*UpdateRequest, error)

func (*UpdateRequest) Fields

func (r *UpdateRequest) Fields() *FieldSet

func (*UpdateRequest) ResourceId

func (r *UpdateRequest) ResourceId() int64

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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