resource

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License: MIT Imports: 12 Imported by: 165

Documentation

Overview

Package resource defines and manages the resource graph and handle the interface with the resource storage handler.

This package is part of the rest-layer project. See http://rest-layer.io for full REST Layer documentation.

Index

Constants

This section is empty.

Variables

View Source
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,
	}
)
View Source
var (
	// ErrNotFound is returned when the requested resource can't be found.
	ErrNotFound = errors.New("Not Found")
	// ErrForbidden is returned when the requested resource can not be accessed
	// by the requestor for security reason.
	ErrForbidden = errors.New("Forbidden")
	// 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")
)
View Source
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.

View Source
var LoggerLevel = LogLevelInfo

LoggerLevel sets the logging level of the framework.

Functions

This section is empty.

Types

type ClearEventHandler

type ClearEventHandler interface {
	OnClear(ctx context.Context, q *query.Query) error
}

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

type ClearEventHandlerFunc func(ctx context.Context, q *query.Query) error

ClearEventHandlerFunc converts a function into a GetEventHandler.

func (ClearEventHandlerFunc) OnClear

OnClear implements ClearEventHandler

type ClearedEventHandler

type ClearedEventHandler interface {
	OnCleared(ctx context.Context, q *query.Query, 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

type ClearedEventHandlerFunc func(ctx context.Context, q *query.Query, deleted *int, err *error)

ClearedEventHandlerFunc converts a function into a FoundEventHandler.

func (ClearedEventHandlerFunc) OnCleared

func (e ClearedEventHandlerFunc) OnCleared(ctx context.Context, q *query.Query, deleted *int, err *error)

OnCleared implements ClearedEventHandler

type Compiler added in v0.2.0

type Compiler interface {
	Compile() error
}

Compiler is an optional interface for Index that's task is to prepare the index for usage. When the method exists, it's automatically called by rest.NewHandler(). When the resource package is used without the rest package, it's the user's responsibilty to call this method.

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 default,
	// 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
	// explicitly 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

func (c Conf) IsModeAllowed(mode Mode) bool

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 query filter.
	Count(ctx context.Context, q *query.Query) (int, error)
}

Counter is an optional interface a Storer can implement to provide a way to explicitly count the total number of elements a given query would return. This method is called by REST Layer when the storage handler returned -1 as ItemList.Total and the user (or configuration) explicitly request the total.

type DeleteEventHandler

type DeleteEventHandler interface {
	OnDelete(ctx context.Context, item *Item) error
}

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

type DeleteEventHandlerFunc func(ctx context.Context, item *Item) error

DeleteEventHandlerFunc converts a function into a GetEventHandler.

func (DeleteEventHandlerFunc) OnDelete

func (e DeleteEventHandlerFunc) OnDelete(ctx context.Context, item *Item) error

OnDelete implements DeleteEventHandler

type DeletedEventHandler

type DeletedEventHandler interface {
	OnDeleted(ctx context.Context, item *Item, err *error)
}

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

type DeletedEventHandlerFunc func(ctx context.Context, item *Item, err *error)

DeletedEventHandlerFunc converts a function into a FoundEventHandler.

func (DeletedEventHandlerFunc) OnDeleted

func (e DeletedEventHandlerFunc) OnDeleted(ctx context.Context, item *Item, err *error)

OnDeleted implements DeletedEventHandler

type FindEventHandler

type FindEventHandler interface {
	OnFind(ctx context.Context, q *query.Query) 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

type FindEventHandlerFunc func(ctx context.Context, q *query.Query) error

FindEventHandlerFunc converts a function into a FindEventHandler.

func (FindEventHandlerFunc) OnFind

OnFind implements 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, query *query.Query, 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

type FoundEventHandlerFunc func(ctx context.Context, q *query.Query, list **ItemList, err *error)

FoundEventHandlerFunc converts a function into a FoundEventHandler.

func (FoundEventHandlerFunc) OnFound

func (e FoundEventHandlerFunc) OnFound(ctx context.Context, q *query.Query, list **ItemList, err *error)

OnFound implements FoundEventHandler

type GetEventHandler

type GetEventHandler interface {
	OnGet(ctx context.Context, id interface{}) error
}

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

type GetEventHandlerFunc func(ctx context.Context, id interface{}) error

GetEventHandlerFunc converts a function into a GetEventHandler.

func (GetEventHandlerFunc) OnGet

func (e GetEventHandlerFunc) OnGet(ctx context.Context, id interface{}) error

OnGet implements GetEventHandler

type GotEventHandler

type GotEventHandler interface {
	OnGot(ctx context.Context, item **Item, err *error)
}

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

type GotEventHandlerFunc func(ctx context.Context, item **Item, err *error)

GotEventHandlerFunc converts a function into a FoundEventHandler.

func (GotEventHandlerFunc) OnGot

func (e GotEventHandlerFunc) OnGot(ctx context.Context, item **Item, err *error)

OnGot implements GotEventHandler

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 retrieves 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.

func NewIndex

func NewIndex() Index

NewIndex creates a new resource index.

type InsertEventHandler

type InsertEventHandler interface {
	OnInsert(ctx context.Context, items []*Item) error
}

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

type InsertEventHandlerFunc func(ctx context.Context, items []*Item) error

InsertEventHandlerFunc converts a function into a GetEventHandler.

func (InsertEventHandlerFunc) OnInsert

func (e InsertEventHandlerFunc) OnInsert(ctx context.Context, items []*Item) error

OnInsert implements InsertEventHandler

type InsertedEventHandler

type InsertedEventHandler interface {
	OnInserted(ctx context.Context, items []*Item, err *error)
}

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

type InsertedEventHandlerFunc func(ctx context.Context, items []*Item, err *error)

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.

func NewItem

func NewItem(payload map[string]interface{}) (*Item, error)

NewItem creates a new item from a payload.

func (*Item) GetField

func (i *Item) GetField(name string) interface{}

GetField returns the item's payload field by its name.

A field name may use the dot notation to reference a sub field. A GetField on field.subfield is equivalent to item.Payload["field"]["subfield"].

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 LogLevel

type LogLevel int

LogLevel defines log levels

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
	LogLevelFatal
)

Log levels

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 Resource

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

Resource holds information about a class of items exposed on the API.

func (*Resource) Alias

func (r *Resource) Alias(name string, v url.Values)

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

func (r *Resource) Bind(name, field string, s schema.Schema, h Storer, c Conf) *Resource

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

func (r *Resource) Clear(ctx context.Context, q *query.Query) (deleted int, err error)

Clear implements Storer interface.

func (*Resource) Compile

func (r *Resource) Compile(rc schema.ReferenceChecker) error

Compile the resource graph and report any error.

func (*Resource) Conf

func (r *Resource) Conf() Conf

Conf returns the resource's configuration.

func (*Resource) Delete

func (r *Resource) Delete(ctx context.Context, item *Item) (err error)

Delete implements Storer interface.

func (*Resource) Find

func (r *Resource) Find(ctx context.Context, q *query.Query) (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, q *query.Query) (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 ErrNotImplemented error is returned.

func (*Resource) Get

func (r *Resource) Get(ctx context.Context, id interface{}) (item *Item, err error)

Get get one item by its id. If item is not found, ErrNotFound error is returned.

func (*Resource) GetAlias

func (r *Resource) GetAlias(name string) (url.Values, bool)

GetAlias returns the alias set for the name if any.

func (*Resource) GetAliases

func (r *Resource) GetAliases() []string

GetAliases returns all the alias names set on the resource.

func (*Resource) GetResources

func (r *Resource) GetResources() []*Resource

GetResources returns first level resources.

func (*Resource) Insert

func (r *Resource) Insert(ctx context.Context, items []*Item) (err error)

Insert implements Storer interface.

func (*Resource) MultiGet

func (r *Resource) MultiGet(ctx context.Context, ids []interface{}) (items []*Item, err error)

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

func (r *Resource) Name() string

Name returns the name of the resource

func (*Resource) ParentField

func (r *Resource) ParentField() string

ParentField returns the name of the field on which the resource is bound to its parent if any.

func (*Resource) Path

func (r *Resource) Path() string

Path returns the full path of the resource composed of names of each intermediate resources separated by dots (i.e.: res1.res2.res3).

func (*Resource) Schema

func (r *Resource) Schema() schema.Schema

Schema returns the resource's schema.

func (*Resource) Update

func (r *Resource) Update(ctx context.Context, item *Item, original *Item) (err error)

Update implements Storer interface.

func (*Resource) Use

func (r *Resource) Use(e interface{}) error

Use attaches an event handler to the resource. This event handler must implement on of the resource.*EventHandler interface or this method returns an error.

func (*Resource) Validator

func (r *Resource) Validator() schema.Validator

Validator returns the resource's validator.

type Storer

type Storer interface {
	// Find searches for items in the backend store matching the q argument. The
	// Window of the query 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 explicitly request the total.
	//
	// The whole query must be treated. If a query predicate operation or sort
	// is not implemented by the storage handler, a resource.ErrNotImplemented
	// must be returned.
	//
	// A storer must ignore the Projection part of the query and always return
	// the document in its entirety. Documents matching a given predicate might
	// be reused (i.e.: cached) with a different projection.
	//
	// 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, q *query.Query) (*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 guarantied 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 query. When possible, the number of
	// items removed is returned, otherwise -1 is return as the first value.
	//
	// The whole query must be treated. If a query predicate operation or sort
	// 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, q *query.Query) (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

type UpdateEventHandlerFunc func(ctx context.Context, item *Item, original *Item) error

UpdateEventHandlerFunc converts a function into a GetEventHandler.

func (UpdateEventHandlerFunc) OnUpdate

func (e UpdateEventHandlerFunc) OnUpdate(ctx context.Context, item *Item, original *Item) error

OnUpdate implements UpdateEventHandler

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

type UpdatedEventHandlerFunc func(ctx context.Context, item *Item, original *Item, err *error)

UpdatedEventHandlerFunc converts a function into a FoundEventHandler.

func (UpdatedEventHandlerFunc) OnUpdated

func (e UpdatedEventHandlerFunc) OnUpdated(ctx context.Context, item *Item, original *Item, err *error)

OnUpdated implements UpdatedEventHandler

Directories

Path Synopsis
testing
mem
Package mem is an example REST backend storage that stores everything in memory.
Package mem is an example REST backend storage that stores everything in memory.

Jump to

Keyboard shortcuts

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