Movatterモバイル変換


[0]ホーム

URL:


resource

package
v0.2.0Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License:MITImports:12Imported by:187

Details

Repository

github.com/rs/rest-layer

Links

Documentation

Overview

Package resource defines and manages the resource graph and handle the interfacewith the resource storage handler.

This package is part of the rest-layer project. Seehttp://rest-layer.io forfull 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(ctxcontext.Context, levelLogLevel, msgstring, fields map[string]interface{}) {log.Output(2, msg)}

Logger is the function used by rest-layer to log messages. By defaultit 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

typeClearEventHandler

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

ClearEventHandler is an interface to be implemented by an event handler thatwant to be called before a resource is cleared. This interface is to be usedwith resource.Use() method.

typeClearEventHandlerFunc

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

ClearEventHandlerFunc converts a function into a GetEventHandler.

func (ClearEventHandlerFunc)OnClear

OnClear implements ClearEventHandler

typeClearedEventHandler

type ClearedEventHandler interface {OnCleared(ctxcontext.Context, q *query.Query, deleted *int, err *error)}

ClearedEventHandler is an interface to be implemented by an event handlerthat want to be called after a resource has been cleared. This interface isto be used with resource.Use() method.

typeClearedEventHandlerFunc

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

ClearedEventHandlerFunc converts a function into a FoundEventHandler.

func (ClearedEventHandlerFunc)OnCleared

func (eClearedEventHandlerFunc) OnCleared(ctxcontext.Context, q *query.Query, deleted *int, err *error)

OnCleared implements ClearedEventHandler

typeCompileradded inv0.2.0

type Compiler interface {Compile()error}

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

typeConf

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.PaginationDefaultLimitint// 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.ForceTotalForceTotalMode}

Conf defines the configuration for a given resource.

func (Conf)IsModeAllowed

func (cConf) IsModeAllowed(modeMode)bool

IsModeAllowed returns true if the provided mode is allowed in the configuration.

typeCounter

type Counter interface {// Count returns the total number of item in the collection given the// provided query filter.Count(ctxcontext.Context, q *query.Query) (int,error)}

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

typeDeleteEventHandler

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

DeleteEventHandler is an interface to be implemented by an event handler thatwant to be called before an item is deleted on a resource. This interface isto be used with resource.Use() method.

typeDeleteEventHandlerFunc

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

DeleteEventHandlerFunc converts a function into a GetEventHandler.

func (DeleteEventHandlerFunc)OnDelete

func (eDeleteEventHandlerFunc) OnDelete(ctxcontext.Context, item *Item)error

OnDelete implements DeleteEventHandler

typeDeletedEventHandler

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

DeletedEventHandler is an interface to be implemented by an event handler thatwant to be called before an item has been deleted on a resource. This interface isto be used with resource.Use() method.

typeDeletedEventHandlerFunc

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

DeletedEventHandlerFunc converts a function into a FoundEventHandler.

func (DeletedEventHandlerFunc)OnDeleted

func (eDeletedEventHandlerFunc) OnDeleted(ctxcontext.Context, item *Item, err *error)

OnDeleted implements DeletedEventHandler

typeFindEventHandler

type FindEventHandler interface {OnFind(ctxcontext.Context, q *query.Query)error}

FindEventHandler is an interface to be implemented by an event handler thatwant to be called before a find is performed on a resource. This interface isto be used with resource.Use() method.

typeFindEventHandlerFunc

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

FindEventHandlerFunc converts a function into a FindEventHandler.

func (FindEventHandlerFunc)OnFind

OnFind implements FindEventHandler

typeForceTotalMode

type ForceTotalModeint

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.TotalOptInForceTotalMode =iota// TotalAlways always force the total number of items on list requestsTotalAlways// 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)

typeFoundEventHandler

type FoundEventHandler interface {OnFound(ctxcontext.Context, query *query.Query, list **ItemList, err *error)}

FoundEventHandler is an interface to be implemented by an event handler thatwant to be called after a find has been performed on a resource. Thisinterface is to be used with resource.Use() method.

typeFoundEventHandlerFunc

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

FoundEventHandlerFunc converts a function into a FoundEventHandler.

func (FoundEventHandlerFunc)OnFound

func (eFoundEventHandlerFunc) OnFound(ctxcontext.Context, q *query.Query, list **ItemList, err *error)

OnFound implements FoundEventHandler

typeGetEventHandler

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

GetEventHandler is an interface to be implemented by an event handler thatwant to be called before a get is performed on a resource. This interface isto be used with resource.Use() method.

typeGetEventHandlerFunc

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

GetEventHandlerFunc converts a function into a GetEventHandler.

func (GetEventHandlerFunc)OnGet

func (eGetEventHandlerFunc) OnGet(ctxcontext.Context, id interface{})error

OnGet implements GetEventHandler

typeGotEventHandler

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

GotEventHandler is an interface to be implemented by an event handler thatwant to be called after a get has been performed on a resource. Thisinterface is to be used with resource.Use() method.

typeGotEventHandlerFunc

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

GotEventHandlerFunc converts a function into a FoundEventHandler.

func (GotEventHandlerFunc)OnGot

func (eGotEventHandlerFunc) OnGot(ctxcontext.Context, item **Item, err *error)

OnGot implements GotEventHandler

typeIndex

type Index interface {// Bind a new resource at the "name" endpointBind(namestring, sschema.Schema, hStorer, cConf) *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(pathstring, parent *Resource) (*Resource,bool)// GetResources returns first level resources.GetResources() []*Resource}

Index is an interface defining a type able to bind and retrieve resourcesfrom a resource graph.

funcNewIndex

func NewIndex()Index

NewIndex creates a new resource index.

typeInsertEventHandler

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

InsertEventHandler is an interface to be implemented by an event handler thatwant to be called before an item is inserted on a resource. This interface isto be used with resource.Use() method.

typeInsertEventHandlerFunc

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

InsertEventHandlerFunc converts a function into a GetEventHandler.

func (InsertEventHandlerFunc)OnInsert

func (eInsertEventHandlerFunc) OnInsert(ctxcontext.Context, items []*Item)error

OnInsert implements InsertEventHandler

typeInsertedEventHandler

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

InsertedEventHandler is an interface to be implemented by an event handlerthat want to be called before an item has been inserted on a resource. Thisinterface is to be used with resource.Use() method.

typeInsertedEventHandlerFunc

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

InsertedEventHandlerFunc converts a function into a FoundEventHandler.

func (InsertedEventHandlerFunc)OnInserted

func (eInsertedEventHandlerFunc) OnInserted(ctxcontext.Context, items []*Item, err *error)

OnInserted implements InsertedEventHandler

typeItem

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.ETagstring// Updated stores the last time the item was updated. This field is used to// populate the Last-Modified header and to handle conditional requests.Updatedtime.Time// Payload the actual data of the itemPayload map[string]interface{}}

Item represents an instance of an item.

funcNewItem

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

NewItem creates a new item from a payload.

func (*Item)GetField

func (i *Item) GetField(namestring) 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 onfield.subfield is equivalent to item.Payload["field"]["subfield"].

typeItemList

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.Totalint// Offset is the index of the first item of the list in the global// collection.Offsetint// Limit is the max number of items requested.Limitint// Items is the list of items contained in the current page given the// current context.Items []*Item}

ItemList represents a list of items

typeLogLevel

type LogLevelint

LogLevel defines log levels

const (LogLevelDebugLogLevel =iotaLogLevelInfoLogLevelWarnLogLevelErrorLogLevelFatal)

Log levels

typeMode

type Modeint

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.CreateMode =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)

typeMultiGetter

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(ctxcontext.Context, ids []interface{}) ([]*Item,error)}

MultiGetter is an optional interface a Storer can implement when the storageengine is able to perform optimized multi gets. REST Layer will automaticallyuse MultiGet over Find whenever it's possible when a storage handlerimplements this interface.

typeResource

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(namestring, vurl.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, fieldstring, sschema.Schema, hStorer, cConf) *Resource

Bind a sub-resource with the provided name. The field parameter defines the parentresource'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 boundor if the specified field doesn't exist in the parent resource spec.

func (*Resource)Clear

func (r *Resource) Clear(ctxcontext.Context, q *query.Query) (deletedint, errerror)

Clear implements Storer interface.

func (*Resource)Compile

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(ctxcontext.Context, item *Item) (errerror)

Delete implements Storer interface.

func (*Resource)Find

func (r *Resource) Find(ctxcontext.Context, q *query.Query) (list *ItemList, errerror)

Find calls the Find method on the storage handler with the corresponding pre/post hooks.

func (*Resource)FindWithTotal

func (r *Resource) FindWithTotal(ctxcontext.Context, q *query.Query) (list *ItemList, errerror)

FindWithTotal calls the Find method on the storage handler with thecorresponding pre/post hooks. If the storage is not able to compute thetotal, this method will call the Count method on the storage. If the storageFind does not compute the total and the Counter interface is not implemented,an ErrNotImplemented error is returned.

func (*Resource)Get

func (r *Resource) Get(ctxcontext.Context, id interface{}) (item *Item, errerror)

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

func (*Resource)GetAlias

func (r *Resource) GetAlias(namestring) (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(ctxcontext.Context, items []*Item) (errerror)

Insert implements Storer interface.

func (*Resource)MultiGet

func (r *Resource) MultiGet(ctxcontext.Context, ids []interface{}) (items []*Item, errerror)

MultiGet get some items by their id and return them in the same order. If oneor 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 toits parent if any.

func (*Resource)Path

func (r *Resource) Path()string

Path returns the full path of the resource composed of names of eachintermediate 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(ctxcontext.Context, item *Item, original *Item) (errerror)

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 mustimplement on of the resource.*EventHandler interface or this method returnsan error.

func (*Resource)Validator

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

Validator returns the resource's validator.

typeStorer

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

Storer defines the interface of an handler able to store and retrieve resources

typeUpdateEventHandler

type UpdateEventHandler interface {OnUpdate(ctxcontext.Context, item *Item, original *Item)error}

UpdateEventHandler is an interface to be implemented by an event handler thatwant to be called before an item is updated for a resource. This interface isto be used with resource.Use() method.

typeUpdateEventHandlerFunc

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

UpdateEventHandlerFunc converts a function into a GetEventHandler.

func (UpdateEventHandlerFunc)OnUpdate

func (eUpdateEventHandlerFunc) OnUpdate(ctxcontext.Context, item *Item, original *Item)error

OnUpdate implements UpdateEventHandler

typeUpdatedEventHandler

type UpdatedEventHandler interface {OnUpdated(ctxcontext.Context, item *Item, original *Item, err *error)}

UpdatedEventHandler is an interface to be implemented by an event handlerthat want to be called before an item has been updated for a resource. Thisinterface is to be used with resource.Use() method.

typeUpdatedEventHandlerFunc

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

UpdatedEventHandlerFunc converts a function into a FoundEventHandler.

func (UpdatedEventHandlerFunc)OnUpdated

func (eUpdatedEventHandlerFunc) OnUpdated(ctxcontext.Context, item *Item, original *Item, err *error)

OnUpdated implements UpdatedEventHandler

Source Files

View all Source files

Directories

PathSynopsis
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 orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp