fire

package module
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2016 License: MIT Imports: 11 Imported by: 1

README

Logo

Go on Fire

Build Status Coverage Status GoDoc Release Go Report Card

An idiomatic micro-framework for building Ember.js compatible APIs with Go.

Go on Fire is built on top of the wonderful built-in http package, implements the JSON API specification through the dedicated jsonapi library, uses the very stable mgo driver for persisting resources wit MongoDB and leverages the dedicated oauth2 library to provide out of the box support for OAuth2 authentication.

The deliberate and tight integration of these components provides a very simple and extensible set of abstractions for rapidly building backend services for websites that use Ember.js as their frontend framework. Of course it can also be used in conjunction with any other single page application framework or as a backend for native mobile applications.

An example application that uses Go on Fire to build an OAuth2 secured JSON API that is consumed by an Ember.js application can be found here: github.com/gonfire/example.

To quickly get started with building an API with Go on Fire follow the quickstart guide, read the detailed sections in this documentation and refer to the package documentation for more detailed information on the used types and methods.

License

The MIT License (MIT)

Copyright (c) 2016 Joël Gähwiler

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func C added in v0.2.5

func C(m Model) string

C is a short-hand function to extract the collection of a model.

func Compose added in v0.2.0

func Compose(chain ...interface{}) http.Handler

Compose is a short-hand for chaining the specified middlewares and handler together.

func Fatal added in v0.2.0

func Fatal(err error) error

Fatal wraps an error and marks it as fatal.

func Validate added in v0.2.4

func Validate(m Model) error

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.

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.

func (Action) Read added in v0.2.0

func (a Action) Read() bool

Read will return true when this action does only read data.

func (Action) Write added in v0.2.0

func (a Action) Write() bool

Write will return true when this action does write data.

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) ID added in v0.2.0

func (b *Base) ID() bson.ObjectId

ID returns the models id.

func (*Base) Meta added in v0.2.0

func (b *Base) Meta() *Meta

Meta returns the models Meta structure.

func (*Base) MustGet added in v0.2.0

func (b *Base) MustGet(name string) interface{}

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

func (b *Base) MustSet(name string, value interface{})

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

type Callback func(*Context) error

A Callback can be an Authorizer or Validator and 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

func DependentResourcesValidator(resources map[string]string) Callback

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.

Resources are defined by passing pairs of collections and fields where the field must be a database field of the target resource model:

DependentResourcesValidator(fire.Map{
	"posts": "user_id",
	"comments": "user_id",
})

func Except added in v0.2.1

func Except(cb Callback, actions ...Action) Callback

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

func MatchingReferencesValidator(collection, reference string, matcher map[string]string) Callback

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("posts", "post_id", fire.Map{
	"user_id": "user_id",
})

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

func Only(cb Callback, actions ...Action) Callback

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

func ProtectedAttributesValidator(attributes map[string]interface{}) Callback

ProtectedAttributesValidator compares protected attributes against their default (during Create) or stored value (during Update) and returns and error if they have been changed.

Attributes are defined by passing pairs of fields and default values:

ProtectedAttributesValidator(fire.Map{
	"title": "A fixed title",
})

func VerifyReferencesValidator added in v0.2.0

func VerifyReferencesValidator(references map[string]string) Callback

VerifyReferencesValidator makes sure all references in the document are existing by counting on the related collections.

References are defined by passing pairs of fields and collections where the field must be a database field on the resource model:

VerifyReferencesValidator(fire.Map{
	"post_id": "posts",
	"user_id": "users",
})

type Context added in v0.2.0

type Context struct {
	// The current action in process.
	Action Action

	// The query that will be used during FindAll, FindOne, Update or Delete.
	// On FindOne, Update and Delete, the "_id" key is preset to the document ID.
	// On FindAll all field filters and relationship filters are preset.
	Query bson.M

	// The Model that will be saved during Create, updated during Update or
	// delete during Delete.
	Model Model

	// The sorting that will be used during FindAll.
	Sorting []string

	// 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
	// contains filtered or unexported fields
}

A Context provides useful contextual information.

func (*Context) Original added in v0.2.0

func (c *Context) Original() (Model, error)

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 are run on all actions. Will cause an Unauthorized status
	// if an user error is returned.
	Authorizers []Callback

	// The Validators are run to validate Create, Update and Delete actions. Will
	// cause a Bad Request status if an user error is returned.
	Validators []Callback

	// The Notifiers are run after any actions has been completed. Will cause
	// a Internal Server Error status if an user error is returned.
	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 listed without a relationship.
	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 {
	Reporter func(error)
	// contains filtered or unexported fields
}

A Group manages access to multiple controllers and their interconnections.

func NewGroup added in v0.2.0

func NewGroup() *Group

NewGroup creates and returns a new group.

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

func (g *Group) Endpoint(prefix string) http.Handler

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.

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

func NewMeta(model Model) *Meta

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

func (m *Meta) FindField(name string) *Field

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

func (m *Meta) Make() Model

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

func (m *Meta) MustFindField(name string) *Field

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.

func Init added in v0.2.0

func Init(model Model) Model

Init initializes the internals of a model and should be called before using a newly created Model.

func InitSlice added in v0.2.0

func InitSlice(ptr interface{}) []Model

InitSlice initializes all models in a slice of the form *[]*Post and returns a new slice that contains all initialized models.

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

func CreateStore(uri string) (*Store, error)

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

func MustCreateStore(uri string) *Store

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) C added in v0.2.0

func (s *Store) C(model Model) *mgo.Collection

C will return the collection associated to the passed model.

func (*Store) Close added in v0.2.0

func (s *Store) Close()

Close will close the store and its associated session.

func (*Store) Copy added in v0.2.0

func (s *Store) Copy() *Store

Copy will make a copy of the store and the underlying session. Copied stores that are not used anymore must be closed.

func (*Store) DB added in v0.2.0

func (s *Store) DB() *mgo.Database

DB returns the database used by this store.

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.

Directories

Path Synopsis
Package auth implements an authenticator component that provides OAuth2 compatible authentication.
Package auth implements an authenticator component that provides OAuth2 compatible authentication.
Package tools implements various helpful tools for developing apps.
Package tools implements various helpful tools for developing apps.

Jump to

Keyboard shortcuts

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