Documentation ¶
Overview ¶
Package fire is an idiomatic micro-framework for building Ember.js compatible APIs with Go.
Index ¶
- Constants
- Variables
- func AssignResource(model coal.Model, res *jsonapi.Resource) error
- func ConvertModel(model coal.Model) (*jsonapi.Resource, error)
- func P(model coal.Model, name string) func(coal.Model) (interface{}, error)
- type Action
- type Callback
- func BasicAuthorizer(credentials map[string]string) *Callback
- func C(name string, s Stage, m Matcher, h Handler) *Callback
- func Combine(name string, stage Stage, cbs ...*Callback) *Callback
- func DependentResourcesValidator(pairs map[coal.Model]string) *Callback
- func MatchingReferencesValidator(reference string, target coal.Model, matcher map[string]string) *Callback
- func ProtectedFieldsValidator(pairs map[string]interface{}) *Callback
- func ReferencedResourcesValidator(pairs map[string]coal.Model) *Callback
- func RelationshipValidator(model coal.Model, models []coal.Model, exclude ...string) *Callback
- func TimestampModifier(createdField, updatedField string) *Callback
- type Client
- func (c *Client) Create(model coal.Model) (coal.Model, *jsonapi.Document, error)
- func (c *Client) Delete(model coal.Model) error
- func (c *Client) Find(model coal.Model, reqs ...jsonapi.Request) (coal.Model, *jsonapi.Document, error)
- func (c *Client) List(model coal.Model, reqs ...jsonapi.Request) ([]coal.Model, *jsonapi.Document, error)
- func (c *Client) Update(model coal.Model) (coal.Model, *jsonapi.Document, error)
- type Context
- type Controller
- type FilterHandler
- type Group
- type GroupAction
- type Handler
- type L
- type M
- type Matcher
- type ModelClient
- func (c *ModelClient[M]) Create(model M) (M, *jsonapi.Document, error)
- func (c *ModelClient[M]) Delete(id coal.ID) error
- func (c *ModelClient[M]) Find(id coal.ID, reqs ...jsonapi.Request) (M, *jsonapi.Document, error)
- func (c *ModelClient[M]) List(reqs ...jsonapi.Request) ([]M, *jsonapi.Document, error)
- func (c *ModelClient[M]) Update(model M) (M, *jsonapi.Document, error)
- type Operation
- type Stage
- type Tester
- func (t *Tester) Assign(prefix string, controllers ...*Controller) *Group
- func (t *Tester) Clean()
- func (t *Tester) DebugRequest(r *http.Request, rr *httptest.ResponseRecorder) string
- func (t *Tester) Path(path string) string
- func (t *Tester) Request(method, path string, payload string, ...)
- func (t *Tester) RunAction(ctx *Context, action *Action) (*httptest.ResponseRecorder, error)
- func (t *Tester) RunCallback(ctx *Context, cb *Callback) error
- func (t *Tester) RunHandler(ctx *Context, h Handler) error
- func (t *Tester) WithContext(ctx *Context, fn func(ctx *Context) error) error
Constants ¶
const NoDefault noDefault = iota
NoDefault marks the specified field to have no default that needs to be enforced while executing the ProtectedFieldsValidator.
Variables ¶
var ErrAccessDenied = xo.BW(jsonapi.ErrorFromStatus(http.StatusUnauthorized, "access denied"))
ErrAccessDenied may be returned to indicate unauthorized access.
var ErrDocumentNotUnique = xo.BW(jsonapi.BadRequest("document not unique"))
ErrDocumentNotUnique may be returned if a provided document does not satisfy the required uniqueness constraints.
var ErrResourceNotFound = xo.BW(jsonapi.NotFound("resource not found"))
ErrResourceNotFound may be returned to indicate a missing resource.
Functions ¶
func AssignResource ¶ added in v0.33.0
AssignResource will assign the provided resource to the specified model.
func ConvertModel ¶ added in v0.33.0
ConvertModel will convert the provided model to a resource.
Types ¶
type Action ¶ added in v0.2.0
type Action struct { // The allowed methods for this action. Methods []string // BodyLimit defines the maximum allowed size of the request body. The // serve.ByteSize helper can be used to set the value. // // Default: 8M. BodyLimit int64 // Timeout defines the time after which the context is cancelled and // processing of the action should be stopped. // // Default: 30s. Timeout time.Duration // The handler that gets executed with the context. // // If returned errors are marked with Safe() they will be included in the // returned JSON-API error. Handler Handler }
An Action defines a collection or resource action.
type Callback ¶ added in v0.2.0
type Callback struct { // The name. Name string // The stage. Stage Stage // The matcher that decides whether the callback should be run. Matcher Matcher // The handler that gets executed with the context. // // If returned errors are marked with Safe() they will be included in the // returned JSON-API error. Handler Handler }
A Callback is called during the request processing flow of a controller.
func BasicAuthorizer ¶ added in v0.8.1
BasicAuthorizer authorizes requests based on a simple credentials list.
func C ¶ added in v0.2.5
C is a shorthand function to construct a callback. It will also add tracing code around the execution of the callback.
func DependentResourcesValidator ¶ added in v0.2.0
DependentResourcesValidator counts related documents and returns an error if some are found. This callback is meant to protect resources from breaking relations when requested to be deleted.
Dependent resources are defined by passing pairs of models and fields that reference the current model.
fire.DependentResourcesValidator(map[coal.Model]string{ &Post{}: "Author", &Comment{}: "Author", })
The callback supports models that use the soft delete mechanism.
func MatchingReferencesValidator ¶ added in v0.2.0
func MatchingReferencesValidator(reference string, target coal.Model, matcher map[string]string) *Callback
MatchingReferencesValidator compares the model with one related model or all related models and checks if the specified references are shared exactly.
The target is defined by passing the reference on the current model and the target model. The matcher is defined by passing pairs of fields on the current and target model:
fire.MatchingReferencesValidator("Blog", &Blog{}, map[string]string{ "Owner": "Owner", })
To-many, optional to-many and has-many relationships are supported both for the initial reference and in the matchers.
func ProtectedFieldsValidator ¶ added in v0.12.0
ProtectedFieldsValidator compares protected fields against their default during Create (if provided) or stored value during Update and returns an error if they have been changed.
Protected fields are defined by passing pairs of fields and default values:
fire.ProtectedFieldsValidator(map[string]interface{}{ "Title": NoDefault, // can only be set during Create "Link": "", // default is fixed and cannot be changed })
The special NoDefault value can be provided to skip the default enforcement on Create.
func ReferencedResourcesValidator ¶ added in v0.20.0
ReferencedResourcesValidator makes sure all references in the document are existing by counting the referenced documents.
References are defined by passing pairs of fields and models which are referenced by the current model:
fire.ReferencedResourcesValidator(map[string]coal.Model{ "Post": &Post{}, "Author": &User{}, })
The callbacks supports to-one, optional to-one and to-many relationships.
func RelationshipValidator ¶ added in v0.8.4
RelationshipValidator makes sure all relationships of a model are correct and in place. It does so by combining a DependentResourcesValidator and a ReferencedResourcesValidator based on the specified model and catalog.
func TimestampModifier ¶ added in v0.28.0
TimestampModifier will set timestamp fields on create and update operations. Missing created timestamps are retroactively set using the timestamp encoded in the model ID.
type Client ¶ added in v0.33.0
type Client struct {
// contains filtered or unexported fields
}
Client wraps a jsonapi.Client to directly interact with models.
func NewClient ¶ added in v0.33.0
func NewClient(client *jsonapi.Client) *Client
NewClient will create and return a new client.
func (*Client) Create ¶ added in v0.33.0
Create will create the provided model and return the created model.
func (*Client) Find ¶ added in v0.33.0
func (c *Client) Find(model coal.Model, reqs ...jsonapi.Request) (coal.Model, *jsonapi.Document, error)
Find will find and return the provided model.
type Context ¶ added in v0.2.0
type Context struct { // The context that is cancelled when the timeout has been exceeded or the // underlying connection transport has been closed. It may also carry the // database session if a transaction is used. // // Values: lungo.ISessionContext?, trace.Span, *xo.Tracer context.Context // The custom data map. Data stick.Map // The current callback stage. Stage Stage // The deferred callbacks. Defers map[Stage][]*Callback // The current operation in process. // // Usage: Read only // Availability: Authorizers Operation Operation // The query that will be used during a List, Find, Update, Delete or // ResourceAction operation to select a list of models or a specific model. // // On Find, Update and Delete operations, the "_id" key is preset to the // resource ID, while on forwarded List operations the relationship filter // is preset. // // Usage: Read only // Availability: Authorizers // Operations: !Create, !CollectionAction Selector bson.M // The filters that will be used during a List, Find, Update, Delete or // ResourceAction operation to further filter the selection of a list of // models or a specific model. // // On List operations, attribute and relationship filters are preset. // // Usage: Append only // Availability: Authorizers // Operations: !Create, !CollectionAction Filters []bson.M // The sorting that will be used during List. // // Usage: No Restriction // Availability: Authorizers // Operations: List Sorting []string // Only the whitelisted readable fields are exposed to the client as // attributes and relationships. Additionally, only readable fields can // be used for filtering and sorting. // // Usage: Reduce only // Availability: Authorizers // Operations: !Delete, !ResourceAction, !CollectionAction ReadableFields []string // Used instead of ReadableFields if set. Allows specifying readable fields // on a per model basis. The model is nil during the initial load of fields // during a List operation. Returned list must be a subset of ReadableFields. GetReadableFields func(coal.Model) []string // Only the whitelisted writable fields can be altered by requests. // // Usage: Reduce only // Availability: Authorizers // Operations: Create, Update WritableFields []string // Used instead of WritableFields if set. Allows specifying writable fields // on a per model basis. The model is zero when getting the writable fields // during a Create operation. Returned list must be a subset of WritableFields. GetWritableFields func(coal.Model) []string // Only the whitelisted readable properties are exposed to the client as // attributes. // // Usage: Reduce only // Availability: Authorizers // Operations: !Delete, !ResourceActon, !CollectionAction ReadableProperties []string // Used instead of ReadableProperties if set. Allows specifying readable // properties on a per model basis. Returned list must be a subset of // ReadableProperties. GetReadableProperties func(coal.Model) []string // The filters that will be applied when loading has one and has many // relationships. // // Usage: Append only // Availability: Authorizers. // Operations: !Create, !CollectionAction RelationshipFilters map[string][]bson.M // The model that will be created, updated, deleted or is requested by a // resource action. // // Usage: Modify only // Availability: Validators // Operations: Create, Update, Delete, ResourceAction Model coal.Model // The models that will be returned for a List operation. // // Usage: Modify only // Availability: Decorators // Operations: List Models []coal.Model // The original model that is being updated. Can be used to lookup up // original values of changed fields. // // Usage: Ready only // Availability: Validators // Operations: Update Original coal.Model // The model from the which the related resources are loaded. // // Usage: Read only // Availability: Authorizers // Operations: List?, Find? Parent coal.Model // The document that has been received by the client. // // Usage: Read only // Availability: Authorizers // Operations: !List, !Find, !CollectionAction, !ResourceAction Request *jsonapi.Document // The document that will be written to the client. // // Usage: Modify only // Availability: Notifiers // Operations: !CollectionAction, !ResourceAction Response *jsonapi.Document // The status code that will be written to the client. // // Usage: Modify only // Availability: Notifiers // Operations: !CollectionAction, !ResourceAction ResponseCode int // The store that is used to retrieve and persist the model. // // Usage: Read only Store *coal.Store // The underlying JSON-API request. // // Usage: Read only JSONAPIRequest *jsonapi.Request // The underlying HTTP request. // // Note: The path is not updated when a controller forwards a request to // a related controller. // // Usage: Read only HTTPRequest *http.Request // The underlying HTTP response writer. The response writer should only be // used during collection or resource actions to write a custom response. // // Usage: Read only ResponseWriter http.ResponseWriter // The controller that is managing the request. // // Usage: Read only Controller *Controller // The group that received the request. // // Usage: Read only Group *Group // The current tracer. // // Usage: Read only Tracer *xo.Tracer }
Context carries the state of a request and allows callbacks to influence the processing of a request.
func (*Context) Defer ¶ added in v0.32.0
Defer will defer the provided handler and run it after all controller callbacks have been run at the specified stages.
func (*Context) Modified ¶ added in v0.28.0
Modified will return whether the specified field has been changed. During an update operation the modification is checked against the original model. For all other operations, the field is checked against its zero value.
func (*Context) Parse ¶ added in v0.20.0
Parse will decode a custom JSON body to the specified value.
type Controller ¶ added in v0.2.0
type Controller struct { // The model that this controller should provide (e.g. &Foo{}). Model coal.Model // The store that is used to retrieve and persist the model. Store *coal.Store // Supported may be set to limit the supported operations of a controller. // By default, all operations are supported. If the operation is not // supported the request will be aborted with an unsupported method error. Supported Matcher // Search will enable full text search. // // Note: The "search" query parameter is for searching. Search bool // Filters is a list of fields that are filterable. Only fields that are // exposed and indexed should be made filterable. // // Note: The filter[field] query parameters are used for filtering. Filters []string // FilterHandlers is a map of custom filter handlers that convert filter // values into a filter expression. Handlers thar return a nil or empty // expression will delegate the handling to the default filter algorithm. FilterHandlers map[string]FilterHandler // Sorters is a list of fields that are sortable. Only fields that are // exposed and indexed should be made sortable. // // Note: The "sort" query parameters is used for sorting. Sorters []string // Properties is a mapping of model properties to attribute keys. These // properties are called and their result set as attributes before returning // the response. Properties map[string]string // Authorizers authorize the requested operation on the requested resource // and are run before any models are loaded from the store. Returned "safe" // errors will cause the abortion of the request with an unauthorized status. // // The callbacks are expected to return an error if the requester should be // informed about being unauthorized to access the resource, or add filters // to the context to only return accessible resources. The latter improves // privacy as a protected resource would appear as being not found. // // Operations: All Authorizers []*Callback // Verifiers verify the requested operation on the requested resource and // are run after models are loaded from the store. Returned "safe" errors // will cause the abortions of the request with an unauthorized status. // // The callbacks are expected to return an error if the requester should be // informed about being unauthorized to access the resource. // // Operations: !CollectionAction Verifiers []*Callback // Modifiers are run to modify the model during Create, Update and Delete // operations after the model is loaded and the changed attributes have been // assigned during an Update but before the model is validated. Returned // "safe" errors will cause the abortion of the request with a bad request // status. // // The callbacks are expected to modify the model to ensure default values, // aggregate fields or in general add data to the model. // // Operations: Create, Update, Delete Modifiers []*Callback // Validators are run to validate Create, Update and Delete operations // after the model is loaded, got modified and passed basic validation. // Returned "safe" errors will cause the abortion of the request with a bad // request. // // The callbacks are expected to validate the model being created, updated // or deleted and return errors if the presented attributes or relationships // are invalid or do not comply with the stated requirements. Necessary // authorization checks should be repeated and now also include the model's // attributes and relationships. The model should not be further modified to // ensure that the validators do not influence each other. // // Operations: Create, Update, Delete Validators []*Callback // Decorators are run after the models or model have been loaded from the // database for List and Find operations or the model has been saved or // updated for Create and Update operations. // // Operations: !Delete, !ResourceAction, !CollectionAction Decorators []*Callback // Notifiers are run before the final response is written to the client // and provide a chance to modify the response and notify other systems // about the applied changes. // // Operations: !ResourceAction, !CollectionAction Notifiers []*Callback // ListLimit can be set to a value higher than 1 to enforce paginated // responses and restrain the page size to be within one and the limit. // // Note: The "page[number]" and "page[size]" query parameters are used for // offset based pagination. ListLimit int64 // CursorPagination can be set to require cursor based pagination. It can be // enforced by also setting ListLimit. Cursor pagination will use the sort // fields (including _id as the tiebreaker) to return a cursor that can be // used to traverse large collections without incurring the performance // costs of offset based pagination. This also implicitly adds the _id field // as the last sorting field for all queries using pagination. For the // pagination to be stable the filter and sorting fields must also remain // stable between requests. // // Note: The "page[after]", "page[before]" and "page[size]" query parameters // are used for cursor based pagination. CursorPagination bool // DocumentLimit defines the maximum allowed size of an incoming document. // The serve.ByteSize helper can be used to set the value. // // Default: 8M. DocumentLimit int64 // ReadTimeout and WriteTimeout specify the timeouts for read and write // operations. // // Default: 30s. ReadTimeout time.Duration WriteTimeout time.Duration // CollectionActions and ResourceActions are custom actions that are run // on the collection (e.g. "posts/delete-cache") or resource (e.g. // "users/1/recover-password"). The request context is forwarded to // the specified callback after running the authorizers. No validators, // modifiers, decorators and notifiers are run for these requests. CollectionActions map[string]*Action ResourceActions map[string]*Action // TolerateViolations will prevent errors if the specified non-writable // fields are changed during a Create or Update operation. TolerateViolations []string // IdempotentCreate can be set to true to enable the idempotent create // mechanism. When creating resources, clients have to generate and submit a // unique "create token". The controller will then first check if a document // with the supplied token has already been created. The controller will // determine the token field from the provided model using the // "fire-idempotent-create" flag. It is recommended to add a unique index on // the token field and also enable the soft delete mechanism to prevent // duplicates if a short-lived document has already been deleted. IdempotentCreate bool // ConsistentUpdate can be set to true to enable the consistent update // mechanism. When updating a resource, the client has to first load the // most recent resource and retain the server generated "update token" and // send it with the update in the defined update token field. The controller // will then check if the stored document still has the same token. The // controller will determine the token field from the provided model using // the "fire-consistent-update" flag. ConsistentUpdate bool // SoftDelete can be set to true to enable the soft delete mechanism. If // enabled, the controller will flag documents as deleted instead of // immediately removing them. It will also exclude soft deleted documents // from queries. The controller will determine the timestamp field from the // provided model using the "fire-soft-delete" flag. It is advised to create // a TTL index to delete the documents automatically after some timeout. SoftDelete bool // contains filtered or unexported fields }
A Controller provides a JSON API based interface to a model.
Database transactions are automatically used for list, find, create, update and delete operations. The created session can be accessed through the context to use it in callbacks.
Note: A controller must not be modified after being added to a group.
type FilterHandler ¶ added in v0.32.0
FilterHandler defines a function that turns filter values into a filter expression.
type Group ¶ added in v0.2.0
type Group struct {
// contains filtered or unexported fields
}
A Group manages access to multiple controllers and their interconnections.
func (*Group) Add ¶ added in v0.2.0
func (g *Group) Add(controllers ...*Controller)
Add will add controllers to the group.
func (*Group) Endpoint ¶ added in v0.2.0
Endpoint will return a handler that serves requests for this group. The specified prefix is used to parse the requests and generate URLs for the resources.
func (*Group) Handle ¶ added in v0.14.1
func (g *Group) Handle(name string, a *GroupAction)
Handle allows to add an action as a group action. Group actions will only be run when no controller matches the request.
type GroupAction ¶ added in v0.18.1
type GroupAction struct { // Authorizers authorize the group action and are run before the action. // Returned errors will cause the abortion of the request with an // "Unauthorized" status by default. Authorizers []*Callback // Action is the action that should be executed. Action *Action }
GroupAction defines a group action.
type Handler ¶ added in v0.12.0
Handler is function that takes a context, mutates is to modify the behaviour and response or return an error.
type Matcher ¶ added in v0.12.3
Matcher is a function that makes an assessment of a context and decides whether an operation should be allowed to be carried out.
type ModelClient ¶ added in v0.33.4
ModelClient is model specific client.
func ClientFor ¶ added in v0.33.4
func ClientFor[M coal.Model](c *Client) *ModelClient[M]
ClientFor creates a model specific client for the specified model using the provided generic client.
func (*ModelClient[M]) Create ¶ added in v0.33.4
func (c *ModelClient[M]) Create(model M) (M, *jsonapi.Document, error)
Create will create the provided model and return the created model.
func (*ModelClient[M]) Delete ¶ added in v0.33.4
func (c *ModelClient[M]) Delete(id coal.ID) error
Delete will delete the model with the provided ID.
func (*ModelClient[M]) Find ¶ added in v0.33.4
func (c *ModelClient[M]) Find(id coal.ID, reqs ...jsonapi.Request) (M, *jsonapi.Document, error)
Find will find and return the model with the provided ID.
func (*ModelClient[M]) List ¶ added in v0.33.4
func (c *ModelClient[M]) List(reqs ...jsonapi.Request) ([]M, *jsonapi.Document, error)
List will return a list of models.
func (*ModelClient[M]) Update ¶ added in v0.33.4
func (c *ModelClient[M]) Update(model M) (M, *jsonapi.Document, error)
Update will update the provided model and return the updated model.
type Operation ¶ added in v0.11.0
type Operation int
An Operation indicates the purpose of a yield to a callback in the processing flow of an API request by a controller. These operations may occur multiple times during a single request.
const ( // List operation will be used to authorize the loading of multiple // resources from a collection. // // Note: This operation is also used to load related resources. List Operation = 1 << iota // Find operation will be used to authorize the loading of a specific // resource from a collection. // // Note: This operation is also used to load a specific related resource. Find // Create operation will be used to authorize and validate the creation // of a new resource in a collection. Create // Update operation will be used to authorize the loading and validate // the updating of a specific resource in a collection. // // Note: Updates can include attributes, relationships or both. Update // Delete operation will be used to authorize the loading and validate // the deletion of a specific resource in a collection. Delete // CollectionAction operation will be used to authorize the execution // of a callback for a collection action. CollectionAction // ResourceAction operation will be used to authorize the execution of a // callback for a resource action. ResourceAction )
All the available operations.
func (Operation) Action ¶ added in v0.11.0
Action will return true when the operation is a collection or resource action.
type Stage ¶ added in v0.32.0
type Stage int
Stage defines a controller callback stage.
The available controller callback stages.
type Tester ¶ added in v0.8.0
type Tester struct { *coal.Tester // The handler to be tested. Handler http.Handler // A path prefix e.g. 'api'. Prefix string // The header to be set on all requests and contexts. Header map[string]string // Context to be set on fake requests. Context context.Context }
A Tester provides facilities to the test a fire API.
func (*Tester) Assign ¶ added in v0.8.7
func (t *Tester) Assign(prefix string, controllers ...*Controller) *Group
Assign will create a controller group with the specified controllers and assign in to the Handler attribute of the tester. It will return the created group.
func (*Tester) Clean ¶ added in v0.8.0
func (t *Tester) Clean()
Clean will remove the collections of models that have been registered and reset the header map as well as the context.
func (*Tester) DebugRequest ¶ added in v0.8.0
DebugRequest returns a string of information to debug requests.
func (*Tester) Request ¶ added in v0.8.0
func (t *Tester) Request(method, path string, payload string, callback func(*httptest.ResponseRecorder, *http.Request))
Request will run the specified request against the registered handler. This function can be used to create custom testing facilities.
func (*Tester) RunCallback ¶ added in v0.13.0
RunCallback is a helper to test callbacks.
func (*Tester) RunHandler ¶ added in v0.12.2
RunHandler builds a context and runs the passed handler with it.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package ash implements a highly configurable and callback based ACL that can be used to authorize controller operations in a declarative way.
|
Package ash implements a highly configurable and callback based ACL that can be used to authorize controller operations in a declarative way. |
Package coal provides a mini ORM for mongoDB.
|
Package coal provides a mini ORM for mongoDB. |
Package flame implements an authenticator that provides OAuth2 compatible authentication with JWT tokens.
|
Package flame implements an authenticator that provides OAuth2 compatible authentication with JWT tokens. |