Documentation ¶
Overview ¶
Package resource defines and manages the resource graph and handle the interface with the resource storage handler.
See http://github.com/rs/rest-layer for full REST Layer documentation.
Index ¶
- Variables
- type ClearEventHandler
- type ClearEventHandlerFunc
- type ClearedEventHandler
- type ClearedEventHandlerFunc
- type Conf
- type Counter
- type DeleteEventHandler
- type DeleteEventHandlerFunc
- type DeletedEventHandler
- type DeletedEventHandlerFunc
- type Field
- type FindEventHandler
- type FindEventHandlerFunc
- type ForceTotalMode
- type FoundEventHandler
- type FoundEventHandlerFunc
- type GetEventHandler
- type GetEventHandlerFunc
- type GotEventHandler
- type GotEventHandlerFunc
- type Index
- type InsertEventHandler
- type InsertEventHandlerFunc
- type InsertedEventHandler
- type InsertedEventHandlerFunc
- type Item
- type ItemList
- type LogLevel
- type Lookup
- func (l *Lookup) AddFilter(filter string, v schema.Validator) error
- func (l *Lookup) AddQuery(query schema.Query)
- func (l *Lookup) ApplySelector(ctx context.Context, v schema.Validator, p map[string]interface{}, ...) (map[string]interface{}, error)
- func (l *Lookup) Filter() schema.Query
- func (l *Lookup) SetSelector(s string, v schema.Validator) error
- func (l *Lookup) SetSort(sort string, v schema.Validator) error
- func (l *Lookup) SetSorts(sorts []string)
- func (l *Lookup) Sort() []string
- type Mode
- type MultiGetter
- type ReferenceResolver
- type Resource
- func (r *Resource) Alias(name string, v url.Values)
- func (r *Resource) Bind(name, field string, s schema.Schema, h Storer, c Conf) *Resource
- func (r *Resource) Clear(ctx context.Context, lookup *Lookup) (deleted int, err error)
- func (r *Resource) Compile() error
- func (r *Resource) Conf() Conf
- func (r *Resource) Delete(ctx context.Context, item *Item) (err error)
- func (r *Resource) Find(ctx context.Context, lookup *Lookup, offset, limit int) (list *ItemList, err error)
- func (r *Resource) FindWithTotal(ctx context.Context, lookup *Lookup, offset, limit int) (list *ItemList, err error)
- func (r *Resource) Get(ctx context.Context, id interface{}) (item *Item, err error)
- func (r *Resource) GetAlias(name string) (url.Values, bool)
- func (r *Resource) GetAliases() []string
- func (r *Resource) GetResources() []*Resource
- func (r *Resource) Insert(ctx context.Context, items []*Item) (err error)
- func (r *Resource) MultiGet(ctx context.Context, ids []interface{}) (items []*Item, err error)
- func (r *Resource) Name() string
- func (r *Resource) ParentField() string
- func (r *Resource) Path() string
- func (r *Resource) Schema() schema.Schema
- func (r *Resource) Update(ctx context.Context, item *Item, original *Item) (err error)
- func (r *Resource) Use(e interface{}) error
- func (r *Resource) Validator() schema.Validator
- type Storer
- type UpdateEventHandler
- type UpdateEventHandlerFunc
- type UpdatedEventHandler
- type UpdatedEventHandlerFunc
Constants ¶
This section is empty.
Variables ¶
var ( // ReadWrite is a shortcut for all modes ReadWrite = []Mode{Create, Read, Update, Replace, Delete, List, Clear} // ReadOnly is a shortcut for Read and List modes ReadOnly = []Mode{Read, List} // WriteOnly is a shortcut for Create, Update, Delete modes WriteOnly = []Mode{Create, Update, Replace, Delete, Clear} // DefaultConf defines a configuration with some sensible default parameters. // Mode is read/write and default pagination limit is set to 20 items. DefaultConf = Conf{ AllowedModes: ReadWrite, PaginationDefaultLimit: 20, } )
var ( // ErrNotFound is returned when the requested resource can't be found ErrNotFound = errors.New("Not Found") // requestor for security reason ErrUnauthorized = errors.New("Unauthorized") // ErrConflict happens when another thread or node modified the data concurrently // with our own thread in such a way we can't securely apply the requested changes. ErrConflict = errors.New("Conflict") // ErrNotImplemented happens when a used filter is not implemented by the storage // handler. ErrNotImplemented = errors.New("Not Implemented") // ErrNoStorage is returned when not storage handler has been set on the resource. ErrNoStorage = errors.New("No Storage Defined") )
var Logger = func(ctx context.Context, level LogLevel, msg string, fields map[string]interface{}) { log.Output(2, msg) }
Logger is the function used by rest-layer to log messages. By default it does nothing but you can customize it to plug any logger.
var LoggerLevel = LogLevelInfo
LoggerLevel sets the logging level of the framework.
Functions ¶
This section is empty.
Types ¶
type ClearEventHandler ¶
ClearEventHandler is an interface to be implemented by an event handler that want to be called before a resource is cleared. This interface is to be used with resource.Use() method.
type ClearEventHandlerFunc ¶
ClearEventHandlerFunc converts a function into a GetEventHandler.
type ClearedEventHandler ¶
type ClearedEventHandler interface {
OnCleared(ctx context.Context, lookup *Lookup, deleted *int, err *error)
}
ClearedEventHandler is an interface to be implemented by an event handler that want to be called after a resource has been cleared. This interface is to be used with resource.Use() method.
type ClearedEventHandlerFunc ¶
ClearedEventHandlerFunc converts a function into a FoundEventHandler.
type Conf ¶
type Conf struct { // AllowedModes is the list of Mode allowed for the resource. AllowedModes []Mode // DefaultPageSize defines a default number of items per page. By defaut, // no default page size is set resulting in no pagination if no `limit` parameter // is provided. PaginationDefaultLimit int // ForceTotal controls how total number of items on list request is computed. // By default (TotalOptIn), if the total cannot be computed by the storage // handler for free, no total metadata is returned until the user explicitely // request it using the total=1 query-string parameter. Note that if the // storage cannot compute the total and does not implement the resource.Counter // interface, a "not implemented" error is returned. // // The TotalAlways mode always force the computation of the total (make sure the // storage either compute the total on Find or implement the resource.Counter // interface. // // TotalDenied prevents the user from requesting the total. ForceTotal ForceTotalMode }
Conf defines the configuration for a given resource
func (Conf) IsModeAllowed ¶
IsModeAllowed returns true if the provided mode is allowed in the configuration
type Counter ¶
type Counter interface { // Count returns the total number of item in the collection given the provided // lookup filter. Count(ctx context.Context, lookup *Lookup) (int, error) }
Counter is an optional interface a Storer can implement to provide a way to explicitely count the total number of elements a given lookup would return with no pagination provided. This method is called by REST Layer when the storage handler returned -1 as ItemList.Total and the user (or configuration) explicitely request the total.
type DeleteEventHandler ¶
DeleteEventHandler is an interface to be implemented by an event handler that want to be called before an item is deleted on a resource. This interface is to be used with resource.Use() method.
type DeleteEventHandlerFunc ¶
DeleteEventHandlerFunc converts a function into a GetEventHandler.
type DeletedEventHandler ¶
DeletedEventHandler is an interface to be implemented by an event handler that want to be called before an item has been deleted on a resource. This interface is to be used with resource.Use() method.
type DeletedEventHandlerFunc ¶
DeletedEventHandlerFunc converts a function into a FoundEventHandler.
type Field ¶
type Field struct { // Name is the name of the field as define in the resource's schema. Name string // Alias is the wanted name in the representation. Alias string // Params defines a list of params to be sent to the field's param handler if any. Params map[string]interface{} // Fields holds references to child fields if any Fields []Field }
Field is used with Lookup.selector to reformat the resource representation at runtime using a field selection language inspired by GraphQL.
type FindEventHandler ¶
type FindEventHandler interface {
OnFind(ctx context.Context, lookup *Lookup, offset, limit int) error
}
FindEventHandler is an interface to be implemented by an event handler that want to be called before a find is performed on a resource. This interface is to be used with resource.Use() method.
type FindEventHandlerFunc ¶
FindEventHandlerFunc converts a function into a FindEventHandler.
type ForceTotalMode ¶
type ForceTotalMode int
ForceTotalMode defines Conf.ForceTotal modes
const ( // TotalOptIn allows the end-user to opt-in to forcing the total count by // adding the total=1 query-string parameter. TotalOptIn ForceTotalMode = iota // TotalAlways always force the total number of items on list requests TotalAlways // TotalDenied disallows forcing of the total count, and returns an error // if total=1 is supplied, and the total count is not provided by the // Storer's Find method. TotalDenied )
type FoundEventHandler ¶
type FoundEventHandler interface {
OnFound(ctx context.Context, lookup *Lookup, list **ItemList, err *error)
}
FoundEventHandler is an interface to be implemented by an event handler that want to be called after a find has been performed on a resource. This interface is to be used with resource.Use() method.
type FoundEventHandlerFunc ¶
FoundEventHandlerFunc converts a function into a FoundEventHandler.
type GetEventHandler ¶
GetEventHandler is an interface to be implemented by an event handler that want to be called before a get is performed on a resource. This interface is to be used with resource.Use() method.
type GetEventHandlerFunc ¶
GetEventHandlerFunc converts a function into a GetEventHandler.
type GotEventHandler ¶
GotEventHandler is an interface to be implemented by an event handler that want to be called after a get has been performed on a resource. This interface is to be used with resource.Use() method.
type GotEventHandlerFunc ¶
GotEventHandlerFunc converts a function into a FoundEventHandler.
type Index ¶
type Index interface { // Bind a new resource at the "name" endpoint Bind(name string, s schema.Schema, h Storer, c Conf) *Resource // GetResource retrives a given resource by it's path. // For instance if a resource user has a sub-resource posts, // a users.posts path can be use to retrieve the posts resource. // // If a parent is given and the path starts with a dot, the lookup is started at the // parent's location instead of root's. GetResource(path string, parent *Resource) (*Resource, bool) // GetResources returns first level resources GetResources() []*Resource }
Index is an interface defining a type able to bind and retrieve resources from a resource graph.
type InsertEventHandler ¶
InsertEventHandler is an interface to be implemented by an event handler that want to be called before an item is inserted on a resource. This interface is to be used with resource.Use() method.
type InsertEventHandlerFunc ¶
InsertEventHandlerFunc converts a function into a GetEventHandler.
type InsertedEventHandler ¶
InsertedEventHandler is an interface to be implemented by an event handler that want to be called before an item has been inserted on a resource. This interface is to be used with resource.Use() method.
type InsertedEventHandlerFunc ¶
InsertedEventHandlerFunc converts a function into a FoundEventHandler.
func (InsertedEventHandlerFunc) OnInserted ¶
func (e InsertedEventHandlerFunc) OnInserted(ctx context.Context, items []*Item, err *error)
OnInserted implements InsertedEventHandler
type Item ¶
type Item struct { // ID is used to uniquely identify the item in the resource collection. ID interface{} // ETag is an opaque identifier assigned by REST Layer to a specific version of the item. // // This ETag is used perform conditional requests and to ensure storage handler doesn't // update an outdated version of the resource. ETag string // Updated stores the last time the item was updated. This field is used to populate the // Last-Modified header and to handle conditional requests. Updated time.Time // Payload the actual data of the item Payload map[string]interface{} }
Item represents an instance of an item
type ItemList ¶
type ItemList struct { // Total defines the total number of items in the collection matching the current // context. If the storage handler cannot compute this value, -1 is set. Total int // Offset is the index of the first item of the list in the global collection. Offset int // Limit is the max number of items requested. Limit int // Items is the list of items contained in the current page given the current // context. Items []*Item }
ItemList represents a list of items
type Lookup ¶
type Lookup struct {
// contains filtered or unexported fields
}
Lookup holds filter and sort used to select items in a resource collection
func NewLookupWithQuery ¶
NewLookupWithQuery creates an empty lookup object with a given query
func (*Lookup) AddFilter ¶
AddFilter parses and validate a filter parameter and add it to lookup's filter
The filter query is validated against the provided validator to ensure all queried fields exists and are of the right type.
func (*Lookup) ApplySelector ¶
func (l *Lookup) ApplySelector(ctx context.Context, v schema.Validator, p map[string]interface{}, resolver ReferenceResolver) (map[string]interface{}, error)
ApplySelector applies fields filtering / rename to the payload fields
func (*Lookup) Filter ¶
Filter is a MongoDB inspired query with a more limited set of capabilities.
See https://github.com/rs/rest-layer#filtering for more info.
func (*Lookup) SetSelector ¶
SetSelector parses a selector expression, validates it and assign it to the current Lookup.
func (*Lookup) SetSorts ¶
SetSorts set the sort fields with a pre-parsed list of fields to sort on. This method doesn't validate sort fields.
func (*Lookup) Sort ¶
Sort is a list of resource fields or sub-fields separated by comas (,). To invert the sort, a minus (-) can be prefixed.
See https://github.com/rs/rest-layer#sorting for more info.
type Mode ¶
type Mode int
Mode defines CRUDL modes to be used with Conf.AllowedModes.
const ( // Create mode represents the POST method on a collection URL or the PUT method // on a _non-existing_ item URL. Create Mode = iota // Read mode represents the GET method on an item URL Read // Update mode represents the PATCH on an item URL. Update // Replace mode represents the PUT methods on an existing item URL. Replace // Delete mode represents the DELETE method on an item URL. Delete // Clear mode represents the DELETE method on a collection URL Clear // List mode represents the GET method on a collection URL. List )
type MultiGetter ¶
type MultiGetter interface { // MultiGet retrieves items by their ids and return them an a list. If one or more // item(s) cannot be found, the method must not return a resource.ErrNotFound but // must just omit the item in the result. // // The items in the result are expected to match the order of the requested ids. MultiGet(ctx context.Context, ids []interface{}) ([]*Item, error) }
MultiGetter is an optional interface a Storer can implement when the storage engine is able to perform optimized multi gets. REST Layer will automatically use MultiGet over Find whenever it's possible when a storage handler implements this interface.
type ReferenceResolver ¶
ReferenceResolver is a function resolving a reference to another field
type Resource ¶
type Resource struct {
// contains filtered or unexported fields
}
Resource holds information about a class of items exposed on the API
func (*Resource) Alias ¶
Alias adds an pre-built resource query on /<resource>/<alias>.
// Add a friendly alias to public posts on /users/:user_id/posts/public // (equivalent to /users/:user_id/posts?filter={"public":true}) posts.Alias("public", url.Values{"where": []string{"{\"public\":true}"}})
This method will panic an alias or a resource with the same name is already bound
func (*Resource) Bind ¶
Bind a sub-resource with the provided name. The field parameter defines the parent resource's which contains the sub resource id.
users := api.Bind("users", userSchema, userHandler, userConf) // Bind a sub resource on /users/:user_id/posts[/:post_id] // and reference the user on each post using the "user" field. posts := users.Bind("posts", "user", postSchema, postHandler, postConf)
This method will panic an alias or a resource with the same name is already bound or if the specified field doesn't exist in the parent resource spec.
func (*Resource) Find ¶
func (r *Resource) Find(ctx context.Context, lookup *Lookup, offset, limit int) (list *ItemList, err error)
Find calls the Find method on the storage handler with the corresponding pre/post hooks.
func (*Resource) FindWithTotal ¶
func (r *Resource) FindWithTotal(ctx context.Context, lookup *Lookup, offset, limit int) (list *ItemList, err error)
FindWithTotal calls the Find method on the storage handler with the corresponding pre/post hooks. If the storage is not able to compute the total, this method will call the Count method on the storage. If the storage Find does not compute the total and the Counter interface is not implemented, an ErrNotImpemented error is returned.
func (*Resource) Get ¶
Get get one item by its id. If item is not found, ErrNotFound error is returned
func (*Resource) GetAliases ¶
GetAliases returns all the alias names set on the resource
func (*Resource) GetResources ¶
GetResources returns first level resources
func (*Resource) MultiGet ¶
MultiGet get some items by their id and return them in the same order. If one or more item(s) is not found, their slot in the response is set to nil.
func (*Resource) ParentField ¶
ParentField returns the name of the field on which the resource is bound to its parent if any.
func (*Resource) Path ¶
Path returns the full path of the resource composed of names of each intermediate resources separated by dots (i.e.: res1.res2.res3)
type Storer ¶
type Storer interface { // Find searches for items in the backend store matching the lookup argument. The // pagination argument must be respected. If no items are found, an empty list // should be returned with no error. // // If the total number of item can't be computed for free, ItemList.Total must // be set to -1. Your Storer may implement the Counter interface to let the user // explicitely request the total. // // The whole lookup query must be treated. If a query operation is not implemented // by the storage handler, a resource.ErrNotImplemented must be returned. // // If the fetching of the data is not immediate, the method must listen for cancellation // on the passed ctx. If the operation is stopped due to context cancellation, the // function must return the result of the ctx.Err() method. Find(ctx context.Context, lookup *Lookup, offset, limit int) (*ItemList, error) // Insert stores new items in the backend store. If any of the items does already exist, // no item should be inserted and a resource.ErrConflict must be returned. The insertion // of the items must be performed atomically. If more than one item is provided and the // backend store doesn't support atomical insertion of several items, a // resource.ErrNotImplemented must be returned. // // If the storage of the data is not immediate, the method must listen for cancellation // on the passed ctx. If the operation is stopped due to context cancellation, the // function must return the result of the ctx.Err() method. Insert(ctx context.Context, items []*Item) error // Update replace an item in the backend store by a new version. The ResourceHandler must // ensure that the original item exists in the database and has the same Etag field. // This check should be performed atomically. If the original item is not // found, a resource.ErrNotFound must be returned. If the etags don't match, a // resource.ErrConflict must be returned. // // The item payload must be stored together with the etag and the updated field. // The item.ID and the payload["id"] is garantied to be identical, so there's not need // to store both. // // If the storage of the data is not immediate, the method must listen for cancellation // on the passed ctx. If the operation is stopped due to context cancellation, the // function must return the result of the ctx.Err() method. Update(ctx context.Context, item *Item, original *Item) error // Delete deletes the provided item by its ID. The Etag of the item stored in the // backend store must match the Etag of the provided item or a resource.ErrConflict // must be returned. This check should be performed atomically. // // If the provided item were not present in the backend store, a resource.ErrNotFound // must be returned. // // If the removal of the data is not immediate, the method must listen for cancellation // on the passed ctx. If the operation is stopped due to context cancellation, the // function must return the result of the ctx.Err() method. Delete(ctx context.Context, item *Item) error // Clear removes all items matching the lookup. When possible, the number of items // removed is returned, otherwise -1 is return as the first value. // // The whole lookup query must be treated. If a query operation is not implemented // by the storage handler, a resource.ErrNotImplemented must be returned. // // If the removal of the data is not immediate, the method must listen for cancellation // on the passed ctx. If the operation is stopped due to context cancellation, the // function must return the result of the ctx.Err() method. Clear(ctx context.Context, lookup *Lookup) (int, error) }
Storer defines the interface of an handler able to store and retrieve resources
type UpdateEventHandler ¶
type UpdateEventHandler interface {
OnUpdate(ctx context.Context, item *Item, original *Item) error
}
UpdateEventHandler is an interface to be implemented by an event handler that want to be called before an item is updated for a resource. This interface is to be used with resource.Use() method.
type UpdateEventHandlerFunc ¶
UpdateEventHandlerFunc converts a function into a GetEventHandler.
type UpdatedEventHandler ¶
type UpdatedEventHandler interface {
OnUpdated(ctx context.Context, item *Item, original *Item, err *error)
}
UpdatedEventHandler is an interface to be implemented by an event handler that want to be called before an item has been updated for a resource. This interface is to be used with resource.Use() method.
type UpdatedEventHandlerFunc ¶
UpdatedEventHandlerFunc converts a function into a FoundEventHandler.