Documentation ¶
Index ¶
- Constants
- func A(m Model, field string) string
- func C(m Model) string
- func Compose(chain ...interface{}) http.Handler
- func F(m Model, field string) string
- func Fatal(err error) error
- func Validate(m Model) error
- func ValidateTimestamps(m Model, createdAtField, updatedAtField string)
- type Action
- type Base
- type Callback
- func DependentResourcesValidator(resources map[string]string) Callback
- func Except(cb Callback, actions ...Action) Callback
- func MatchingReferencesValidator(collection, reference string, matcher map[string]string) Callback
- func ModelValidator() Callback
- func Only(cb Callback, actions ...Action) Callback
- func ProtectedAttributesValidator(attributes map[string]interface{}) Callback
- func UniqueAttributeValidator(uniqueAttribute string, filters ...string) Callback
- func VerifyReferencesValidator(references map[string]string) Callback
- type Context
- type Controller
- type Field
- type Group
- type HasMany
- type Meta
- type Model
- type Store
- type ValidatableModel
Constants ¶
const NoDefault value = iota
NoDefault marks the specified field to have no default that needs to be enforced while executing the ProtectedAttributesValidator.
Variables ¶
This section is empty.
Functions ¶
func A ¶ added in v0.5.4
A is a short-hand function to extract the JSON attribute name of a model attribute.
func Compose ¶ added in v0.2.0
Compose is a short-hand for chaining the specified middlewares and handler together.
func F ¶ added in v0.5.4
F is a short-hand function to extract the BSON field name of a model attribute.
func Validate ¶ added in v0.2.4
Validate uses the govalidator package to validate the model based on the "valid" struct tags. If the passed model also implements the ValidatableModel interface, Validate method will be invoked after the struct validation.
func ValidateTimestamps ¶ added in v0.5.5
ValidateTimestamps is a helper function that can be used inside a models Validate method to maintain "created-at" and "updated-at" timestamps.
Note: You can pass an empty string to disable certain timestamps.
Types ¶
type Action ¶ added in v0.2.0
type Action int
An Action describes the currently called action on the API.
const ( List Action Find Create Update Delete )
All the available actions.
type Base ¶ added in v0.2.0
type Base struct { DocID bson.ObjectId `json:"-" bson:"_id,omitempty"` // contains filtered or unexported fields }
Base is the base for every fire model.
func (*Base) MustGet ¶ added in v0.2.0
MustGet returns the value of the given field.
Note: MustGet will return the value of the first field that has a matching Name, JSONName, or BSONName and will panic if no field can be found.
func (*Base) MustSet ¶ added in v0.2.0
MustSet will set the given field to the the passed valued.
Note: MustSet will set the value of the first field that has a matching Name, JSONName, or BSONName and will panic if no field can been found. The method will also panic if the type of the field and the passed value do not match.
type Callback ¶ added in v0.2.0
A Callback is called during execution of a controller.
Note: If the callback returns an error wrapped using Fatal() the API returns an InternalServerError status and the error will be logged. All other errors are serialized to an error object and returned.
func DependentResourcesValidator ¶ added in v0.2.0
DependentResourcesValidator counts documents in the supplied collections and returns an error if some get found. This callback is meant to protect resources from breaking relations when requested to be deleted.
Dependent resources are defined by passing pairs of collections and database fields that hold the current models id:
DependentResourcesValidator(map[string]string{ C(&Post{}): F(&Post{}, "Author"), C(&Comment{}): F(&Comment{}, "Author"), })
func Except ¶ added in v0.2.1
Except will return a callback that runs the specified callback only when none of the supplied actions match.
func MatchingReferencesValidator ¶ added in v0.2.0
MatchingReferencesValidator compares the model with a related model and checks if certain references are shared.
The target model is defined by passing its collection and the referencing field on the current model. The matcher is defined by passing pairs of database fields on the target and current model:
MatchingReferencesValidator(C(&Blog{}), F(&Post{}, "Blog"), map[string]string{ F(&Blog{}, "Owner"): F(&Post{}, "Owner"), })
func ModelValidator ¶ added in v0.2.0
func ModelValidator() Callback
ModelValidator performs a validation of the model using the Validate function.
func Only ¶ added in v0.2.1
Only will return a callback that runs the specified callback only when one of the supplied actions match.
func ProtectedAttributesValidator ¶ added in v0.2.0
ProtectedAttributesValidator compares protected attributes against their default (during Create) or stored value (during Update) and returns an error if they have been changed.
Attributes are defined by passing pairs of fields and default values:
ProtectedAttributesValidator(map[string]interface{}{ F(&Post{}, "Title"): NoDefault, // can only be set during Create F(&Post{}, "Link"): "", // is fixed and cannot be changed })
The special NoDefault value can be provided to skip the default enforcement on Create.
func UniqueAttributeValidator ¶ added in v0.5.1
UniqueAttributeValidator ensures that the specified attribute of the controllers Model will remain unique among the specified filters.
The unique attribute is defines as the first argument. Filters are defined by passing a list of database fields:
UniqueAttributeValidator(F(&Blog{}, "Name"), F(&Blog{}, "Creator"))
func VerifyReferencesValidator ¶ added in v0.2.0
VerifyReferencesValidator makes sure all references in the document are existing by counting the references on the related collections.
References are defined by passing pairs of database fields and collections of models whose ids might be referenced on the current model:
VerifyReferencesValidator(map[string]string{ F(&Comment{}, "Post"): C(&Post{}), F(&Comment{}, "Author"): C(&User{}), })
type Context ¶ added in v0.2.0
type Context struct { // The current action in process. Action Action // The query that will be used during List, Find, Update or Delete to fetch // a list of models or the specific requested model. // // On Find, Update and Delete, the "_id" key is preset to the document ID // while on List all field and relationship filters are preset. Query bson.M // The Model that will be saved during Create, updated during Update or // deleted during Delete. Model Model // The sorting that will be used during List. Sorting []string // The document that will be written to the client during List, Find, Create // and partially Update. The JSON API endpoints to modify a resources // relationships do only respond with a header as no other information should // be changed. Response *jsonapi.Document // The store that is used to retrieve and persist the model. Store *Store // The underlying JSON API request. JSONAPIRequest *jsonapi.Request // The underlying HTTP request. HTTPRequest *http.Request // The Controller that is managing the request. Controller *Controller // The Group that received the request. Group *Group // contains filtered or unexported fields }
A Context provides useful contextual information.
func (*Context) Original ¶ added in v0.2.0
Original will return the stored version of the model. This method is intended to be used to calculate the changed fields during an Update action. Any returned error is already marked as fatal.
Note: The method will panic if being used during any other action than Update.
type Controller ¶ added in v0.2.0
type Controller struct { // The model that this controller should provide (e.g. &Foo{}). Model Model // Filters defines the attributes that are filterable. Filters []string // Sorters defines the attributes that are sortable. Sorters []string // The store that is used to retrieve and persist the model. Store *Store // The Authorizers authorize the requested action on the requested resource // and are run before any models are loaded from the DB. Returned 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 him being unauthorized to access the resource or modify the // Context's Query attribute in such a way that only accessible resources // are returned. The later improves privacy as a protected resource would // just appear as being not found. Authorizers []Callback // The Validators are run to validate Create, Update and Delete actions after // the models are loaded from the DB and the changed attributes have been // assigned during an Update. Returned errors will cause the abortion of the // request with a Bad Request status. // // 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. The preceding // authorization checks should be repeated and now also include the model's // attributes and relationships. Validators []Callback // The 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. Returned errors will cause the abortion of the // request with an Internal Server Error status. Notifiers []Callback // The NoList property can be set to true if the resource is only listed // through relationships from other resources. This is useful for // resources like comments that should never be listed alone. NoList bool // The 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. ListLimit int }
A Controller provides a JSON API based interface to a model.
Note: Controllers must not be modified after adding to an application.
type Field ¶ added in v0.2.0
type Field struct { Name string Type reflect.Type Kind reflect.Kind JSONName string BSONName string Optional bool ToOne bool ToMany bool HasMany bool RelName string RelType string RelInverse string // contains filtered or unexported fields }
A Field contains the meta information about a single field of a model.
type Group ¶ added in v0.2.0
type Group struct { // The Reporter function gets invoked by the controller with any occurring // fatal errors. Reporter func(error) // 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 a controller to the group.
func (*Group) Endpoint ¶ added in v0.2.0
Endpoint will return an http handler that serves requests for this controller group. The specified prefix is used to parse the requests and generate urls for the resources.
func (*Group) Find ¶ added in v0.5.0
func (g *Group) Find(pluralName string) *Controller
Find will return the controller with the matching plural name if found.
func (*Group) List ¶ added in v0.5.0
func (g *Group) List() []*Controller
List will return a list of all added controllers.
type HasMany ¶ added in v0.2.0
type HasMany struct{}
The HasMany type denotes a has many relationship in a model declaration.
type Meta ¶ added in v0.2.0
type Meta struct { Name string PluralName string Collection string Fields []Field // contains filtered or unexported fields }
Meta stores extracted meta data from a model.
func NewMeta ¶ added in v0.2.0
NewMeta returns the Meta structure for the passed Model.
Note: This method panics if the passed Model has invalid fields and tags.
func (*Meta) FindField ¶ added in v0.2.0
FindField returns the first field that has a matching Name, JSONName, or BSONName. FindField will return nil if no field has been found.
func (*Meta) Make ¶ added in v0.2.0
Make returns a pointer to a new zero initialized model e.g. *Post.
Note: Other libraries like mgo might replace the pointer content with a new structure, therefore the model eventually needs to be initialized again using Init().
func (*Meta) MakeSlice ¶ added in v0.2.0
func (m *Meta) MakeSlice() interface{}
MakeSlice returns a pointer to a zero length slice of the model e.g. *[]*Post.
Note: Don't forget to initialize the slice using InitSlice() after adding elements with libraries like mgo.
func (*Meta) MustFindField ¶ added in v0.2.0
MustFindField returns the first field that has a matching Name, JSONName, or BSONName. MustFindField will panic if no field has been found.
type Model ¶ added in v0.2.0
type Model interface { ID() bson.ObjectId Meta() *Meta MustGet(string) interface{} MustSet(string, interface{}) // contains filtered or unexported methods }
Model is the main interface implemented by every fire model embedding Base.
type Store ¶ added in v0.2.0
type Store struct {
// contains filtered or unexported fields
}
A Store manages the usage of database connections.
func CreateStore ¶ added in v0.2.0
CreateStore will dial the passed database and return a new store. It will return an error if the initial connection failed
func MustCreateStore ¶ added in v0.2.0
MustCreateStore will dial the passed database and return a new store. It will panic if the initial connection failed.
func NewStore ¶ added in v0.2.0
func NewStore(session *mgo.Session) *Store
NewStore returns a Store that uses the passed session and its default database.
func (*Store) Close ¶ added in v0.2.0
func (s *Store) Close()
Close will close the store and its associated session.
type ValidatableModel ¶ added in v0.2.2
type ValidatableModel interface { Model // The Validate method that should return normal errors about invalid fields. Validate() error }
The ValidatableModel interface can be additionally implemented to provide a custom validation method that is used by the Validate function.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package auth implements an authentication manager that provides OAuth2 compatible authentication.
|
Package auth implements an authentication manager that provides OAuth2 compatible authentication. |
Package tools implements various helpful tools for developing apps.
|
Package tools implements various helpful tools for developing apps. |