jsonapi

package module
v0.0.0-...-ef2e096 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2016 License: MIT Imports: 13 Imported by: 0

README

jsonapi

GoDoc build status Go Report Card

Documentation

Index

Constants

View Source
const (
	ParamFields     = "fields"
	ParamFilter     = "filter"
	ParamInclude    = "include"
	ParamPage       = "page"
	ParamPageNumber = "page[number]"
	ParamPageSize   = "page[size]"
	ParamPageOffset = "page[offset]"
	ParamPageLimit  = "page[limit]"
	ParamPageCursor = "page[cursor]"
	ParamSort       = "sort"
)

Standard parameter key constants.

View Source
const (
	ErrRelationshipMissing = "Missing required relationship %q."
	ErrRelationshipSingle  = "Relationship %q must be a single resource linkage."
	ErrRelationshipType    = "Relationship %q must have type %q."
)

Resource error format strings.

View Source
const (
	HeaderContentType = "Content-Type"
	HeaderLocation    = "Location"
)

Commonly used header names.

View Source
const (
	Asc  = "ASC"
	Desc = "DESC"
)

SQL expression constants for ascending and descending order.

View Source
const (
	ErrAccept  = "Request must have %q type in Accept header."
	ErrParam   = "Request has invalid parameter %q."
	ErrInclude = "Request has unsupported include %q."
	ErrSort    = "Request has unsupported sort field %q."
	ErrType    = "Resources must have type %q."
)

Validation error format strings.

View Source
const ContentType = "application/vnd.api+json"

ContentType is the Content-Type header value used for JSON API requests and responses.

View Source
const ErrInvalidJSON = "Invalid JSON body: %s"

ErrInvalidJSON is the error format string used when a request's JSON body is invalid.

View Source
const Version = "1.0"

Version is the version of JSON API that this package implements.

View Source
const Wildcard = "*"

Wildcard matches any include path.

Variables

View Source
var (
	ErrClientID = Error{
		Status: http.StatusForbidden,
		Detail: "Resources cannot have client-generated IDs.",
	}
	ErrMissingClientID = Error{
		Status: http.StatusForbidden,
		Detail: "Resources must have client-generated IDs.",
	}
	ErrDataNull = Error{
		Status: http.StatusBadRequest,
		Detail: "Request data cannot be null.",
	}
	ErrDataSingle = Error{
		Status: http.StatusBadRequest,
		Detail: "Request data cannot be a single resource.",
	}
	ErrDataArray = Error{
		Status: http.StatusBadRequest,
		Detail: "Request data cannot be an array of resources.",
	}
)

Validation errors.

Any represents all include paths.

View Source
var RegexpFields = regexp.MustCompile(`^fields\[(.*)\]$`)

RegexpFields matches fields parameter keys. First submatch is the resource type.

View Source
var RegexpStandardParam = regexp.MustCompile(`^[a-z]+$`)

RegexpStandardParam matches strings following the naming convention for standard parameters.

StandardParams is a map containing all standard query parameters defined by JSON API.

Functions

func JoinParamKey

func JoinParamKey(ks []string) string

JoinParamKey joins a parameter key slice into a string.

func NewRequestContext

func NewRequestContext(ctx context.Context, req *Request) context.Context

NewRequestContext returns a context that carries a request.

func NewResponseContext

func NewResponseContext(ctx context.Context, res *Response) context.Context

NewResponseContext returns a context that carries a response.

func SplitComma

func SplitComma(s string) []string

SplitComma splits a comma-separated list as a string into a slice.

func SplitParamKey

func SplitParamKey(k string) []string

SplitParamKey splits a parameter key into a slice. The parameter key may use square bracket syntax to indicate nested values. For example, "key[one][two]" returns the slice [key one two].

func ValidAccept

func ValidAccept(req *http.Request) error

ValidAccept returns an error if the request's Accept header does not contain the JSON API content type.

func ValidClientIDs

func ValidClientIDs(req *http.Request, jreq *Request, require Requirement) error

ValidClientIDs returns an error if the request contains any client-generated IDs that do not meet the given requirement. If the request is not a POST request, then no error will be returned.

func ValidDataTypes

func ValidDataTypes(req *http.Request, jreq *Request, b DataTypeBits) error

ValidDataTypes returns an error if the request data is a type (null, single resource, or array) that is not included in b. If b is zero, then the default depends on the request method. POST and PATCH requests only allow a single resource and all other methods only allow null.

func ValidIncludes

func ValidIncludes(jreq *Request, is Includes) error

ValidIncludes returns an error if the request contains any include paths not found in is.

func ValidParams

func ValidParams(req *http.Request) error

ValidParams returns an error if the request contains any invalid query parameters.

func ValidSorts

func ValidSorts(jreq *Request, ss Sorts) error

ValidSorts returns an error if the request contains any sort field not found in ss.

func ValidType

func ValidType(jreq *Request, t string) error

ValidType returns an error if the request contains any resources with type not equal to t. If t is an empty string, then no error will be returned.

Types

type Attributes

type Attributes map[string]interface{}

Attributes represents an attributes object and stores arbitrary data.

func (Attributes) Bool

func (a Attributes) Bool(k string) bool

Bool returns the value of a bool attribute. It will return false for non-bool or missing attributes.

func (Attributes) Float

func (a Attributes) Float(k string) float64

Float returns the value of a float64 attribute. It will return 0 for non-float64 or missing attributes.

func (Attributes) Int

func (a Attributes) Int(k string) int

Int returns the value of an int attribute. It will return null for non-int or missing attributes.

func (Attributes) NullBool

func (a Attributes) NullBool(k string) null.Bool

NullBool returns the value of a nullable bool attribute. It will return null for non-bool or missing attributes.

func (Attributes) NullFloat

func (a Attributes) NullFloat(k string) null.Float

NullFloat returns the value of a nullable float64 attribute. It will return null for non-float64 or missing attributes.

func (Attributes) NullInt

func (a Attributes) NullInt(k string) null.Int

NullInt returns the value of a nullable int attribute. It will return null for non-int or missing attributes.

func (Attributes) NullString

func (a Attributes) NullString(k string) null.String

NullString returns the value of a nullable string attribute. It will return null for non-string or missing attributes.

func (Attributes) NullTime

func (a Attributes) NullTime(k string) null.Time

NullTime returns the value of a nullable time attribute. It will return null for non-time or missing attributes.

func (Attributes) String

func (a Attributes) String(k string) string

String returns the value of a string attribute or "" for non-string or missing attributes.

func (Attributes) Time

func (a Attributes) Time(k string) time.Time

Time returns the value of a time attribute. It will return the zero time for non-time or missing attributes.

type Data

type Data struct {
	Resource  *Resource
	Resources Resources
}

Data represents a resource or a collection of resources.

func (Data) MarshalJSON

func (d Data) MarshalJSON() ([]byte, error)

MarshalJSON marshals the struct to either a single resource or array of resources.

func (*Data) UnmarshalJSON

func (d *Data) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals JSON into the struct. The JSON can be a single resource or an array of resource.

type DataTypeBits

type DataTypeBits int

DataTypeBits specifies the allowed types for the data field of a request.

const (
	DataNull DataTypeBits = 1 << iota
	DataSingle
	DataArray
)

Possible bit flags for request body data types.

type Error

type Error struct {
	ID     string `json:"id,omitempty"`
	Status int    `json:"status,string,omitempty"`
	Code   string `json:"code,omitempty"`
	Title  string `json:"title,omitempty"`
	Detail string `json:"detail,omitempty"`
	Source Meta   `json:"source,omitempty"`
	Links  Links  `json:"links,omitempty"`
	Meta   Meta   `json:"meta,omitempty"`
}

Error is a JSON API error object.

func (Error) Error

func (e Error) Error() string

Error returns the error details.

type ErrorHandler

type ErrorHandler func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error

ErrorHandler is a context handler that calls a function that can return an error that gets added to the JSON API response.

func (ErrorHandler) ServeHTTP

func (eh ErrorHandler) ServeHTTP(ctx context.Context, rw http.ResponseWriter, req *http.Request)

ServeHTTP calls the function and adds any error returned to the JSON API response.

type Errors

type Errors []Error

Errors is a slice of JSON API error objects.

func (Errors) Error

func (es Errors) Error() string

Error returns all error details as a string.

type Fieldsets

type Fieldsets map[string][]string

Fieldsets defines a map of sparse fieldsets which specifies a slice of allowed fields for resource types. Key is resource type, value is a slice of field names.

type Includes

type Includes []string

Includes stores a slice of resource inclusion paths.

func (Includes) Contains

func (is Includes) Contains(p string) bool

Contains returns true if p is found in is or is contains the wildcard value.

type JSONAPI

type JSONAPI struct {
	Version string `json:"version,omitempty"`
	Meta    Meta   `json:"meta,omitempty"`
}

JSONAPI stores details about this implementation of JSON API.

type Link linkFields

Link represents a hyperlink.

func (Link) MarshalJSON

func (l Link) MarshalJSON() ([]byte, error)

MarshalJSON marshals the link to either a string (if it has no meta data) or an object.

type Links map[string]Link

Links is a map containing multiple links.

type Meta

type Meta map[string]interface{}

Meta stores arbitrary, non-standard data.

type Middleware

type Middleware struct {
	// Includes is a list of relationship paths supported by the include
	// parameter. Use Any to accept all paths.
	Includes Includes

	// Sorts defines the supported sort fields. The expression fields defined
	// here will be copied into the request's sort fields so the expressions
	// will be available to the handler.
	Sorts Sorts

	// The maximum allowed page size and limit. If 0, then no limit is enforced.
	MaxPageSize, MaxPageLimit int

	// ClientIDs configures the validation check for client-generated IDs in the
	// request body. Possible values are Forbidden (the default), Optional, or
	// Required. Only applies to POST requests.
	ClientIDs Requirement

	// Type is the resource type that all resources in the request must have. If
	// this is an empty string, then all types are allowed.
	Type string

	// DataTypes is a bit field that represents the types that are allowed for
	// the request body data. Possible values are DataNull, DataSingle, and/or
	// DataArray. Use OR (`|`) to allow multiple types. The defaults are
	// DataSingle for POST and PATCH requests and DataNull for other methods.
	DataTypes DataTypeBits

	// Handler is the context handler that is called if the request is valid.
	Handler web.ContextHandler
}

Middleware is a middleware context handler that performs some JSON API validation on the current request, adds JSON API request and response objects to the current context for the next handler, and writes the response.

func (Middleware) ServeHTTP

func (mw Middleware) ServeHTTP(ctx context.Context, rw http.ResponseWriter, req *http.Request)

ServeHTTP performs validation, initializes the request and response objects, and calls the next handler.

type Page

type Page struct {
	Number int
	Size   int
	Offset int
	Limit  int
	Cursor string
}

Page stores pagination parameter values.

type Relationship

type Relationship struct {
	Links Links `json:"links,omitempty"`
	Data  *Data `json:"data,omitempty"`
	Meta  Meta  `json:"meta,omitempty"`
}

Relationship represents a relationship object and stores a reference to a resource object.

type Relationships

type Relationships map[string]*Relationship

Relationships is a map of relationship objects.

type Request

type Request struct {
	Data *Data `json:"data"`

	// Params contains the request query parameters.
	Params url.Values `json:"-"`

	// Includes is a list of requested relationship paths. nil means the client
	// did not specify a list.
	Includes Includes `json:"-"`

	// Fieldsets is the sparse fieldsets specified in the request.
	Fieldsets Fieldsets `json:"-"`

	// Sorts contains the sort fields specified in the request.
	Sorts Sorts `json:"-"`

	// Page contains pagination parameter values.
	Page Page `json:"-"`
}

Request contains JSON API request data extracted from an http.Request.

func NewRequest

func NewRequest(req *http.Request) (*Request, error)

NewRequest returns a new request populated from an http.Request.

func RequestFromContext

func RequestFromContext(ctx context.Context) *Request

RequestFromContext returns the request stored in ctx.

func (Request) Filter

func (r Request) Filter(ks ...string) string

Filter returns the value of a filter parameter. If a filter doesn't exist, an empty string is returned. Keys can be given to access nested filters.

func (Request) Include

func (r Request) Include(p string) bool

Include returns true if the given relationship path p should be included in the response. This is true if the request did not specify any includes or p was included in the list of includes.

func (Request) Param

func (r Request) Param(ks ...string) string

Param returns a parameter as a string. If the parameter doesn't exist, an empty string is returned. Multiple keys can be given to access nested parameter values.

func (Request) ParamInt

func (r Request) ParamInt(ks ...string) int

ParamInt is like Param, except it returns an int or 0 if missing or invalid.

func (Request) ParamNonNegInt

func (r Request) ParamNonNegInt(ks ...string) int

ParamNonNegInt is like ParamInt, except negative integers are invalid.

type Requirement

type Requirement int

Requirement represents the possible requirements for client-generated IDs.

const (
	Forbidden Requirement = iota
	Optional
	Required
)

Possible values for Requirement.

type Resource

type Resource struct {
	ID            string        `json:"id"`
	Type          string        `json:"type"`
	Attributes    Attributes    `json:"attributes,omitempty"`
	Relationships Relationships `json:"relationships,omitempty"`
	Links         Links         `json:"links,omitempty"`
	Meta          Meta          `json:"meta,omitempty"`
}

Resource represents a resource object.

func (*Resource) AddSingleLinkage

func (r *Resource) AddSingleLinkage(k, id, t string)

AddSingleLinkage adds a resource linkage object to r's relationships for a single resource. The relationship will have key k and the linked resource has ID id and type t.

func (Resource) LinkageID

func (r Resource) LinkageID(k, t string) (string, error)

LinkageID returns the ID of the resource linkage with relationship key k and an expected type of t.

func (Resource) NullLinkageID

func (r Resource) NullLinkageID(k, t string) (null.String, error)

NullLinkageID returns the ID of an optional resource linkage with relationship key k and an expected type of t.

func (*Resource) Resource

func (r *Resource) Resource() *Resource

Resource returns the resource itself. This implements the Resourcer interface.

func (*Resource) Sparse

func (r *Resource) Sparse(fs Fieldsets)

Sparse removes attributes and relationships not found in the given sparse fieldsets. This also modifies all nested resources found under the resource's relationships.

type Resourcer

type Resourcer interface {
	Resource() *Resource
}

Resourcer is an interface that wraps a Resource method for returning a resource.

type Resourcers

type Resourcers interface {
	Resources() Resources
}

Resourcers is an interface that wraps a Resources method for returning a slice of resources.

type Resources

type Resources []*Resource

Resources is a slice of resources.

func (Resources) IDs

func (rs Resources) IDs() []string

IDs returns a slice of IDs for each resource in rs.

func (Resources) Resources

func (rs Resources) Resources() Resources

Resources returns the resource slice itself. This implements the Resourcers interface.

func (Resources) Sparse

func (rs Resources) Sparse(fs Fieldsets)

Sparse removes attributes and relationships not found in the given sparse fieldsets for all resources in rs. This also modifies all nested resources found under each resource's relationships.

type Response

type Response struct {
	Status int `json:"-"`

	JSONAPI  *JSONAPI  `json:"jsonapi,omitempty"`
	Links    Links     `json:"links,omitempty"`
	Data     *Data     `json:"data,omitempty"`
	Included Resources `json:"included,omitempty"`
	Errors   []Error   `json:"errors,omitempty"`
	Meta     Meta      `json:"meta,omitempty"`

	// Fieldsets defines sparse fieldsets to be applied to all resources in the
	// response when the response is written.
	Fieldsets Fieldsets `json:"-"`
	// contains filtered or unexported fields
}

Response represents a JSON API response document.

func NewResponse

func NewResponse(rw http.ResponseWriter) *Response

NewResponse initializes a new response to be written to rw.

func ResponseFromContext

func ResponseFromContext(ctx context.Context) *Response

ResponseFromContext returns the response stored in ctx.

func (*Response) AddError

func (r *Response) AddError(err error)

AddError adds an error to the response and updates the status code.

func (*Response) AddInclude

func (r *Response) AddInclude(rr Resourcer)

AddInclude adds a single resource to the slice of included resources. If the resource is already in the slice, nothing happens.

func (*Response) AddIncludes

func (r *Response) AddIncludes(rrs Resourcers)

AddIncludes adds all resources in rrs to the slice of included resources. If a resource is already in the slice, it won't be added as a duplicate.

func (*Response) AddResource

func (r *Response) AddResource(rr Resourcer)

AddResource adds a single resource to the response data.

func (*Response) AddResources

func (r *Response) AddResources(rrs Resourcers)

AddResources adds all resources in rrs to the response data.

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the headers for the response.

func (*Response) SetLocation

func (r *Response) SetLocation(url string)

SetLocation sets the Location header to some URL of a created resource.

func (*Response) SetResource

func (r *Response) SetResource(rr Resourcer)

SetResource sets the response data to a single resource.

func (*Response) Write

func (r *Response) Write()

Write writes the entire response to the response writer. This applies sparse fieldsets to all resources to be written. This should only be called once.

type Sort

type Sort struct {
	// Name is the name of the sort field that is used in the sort parameter.
	Name string

	// Expr is the actual expression (or column name) that is prefixed with ASC
	// or DESC depending on the order for this sort field.
	Expr string

	// ExprAsc and ExprDesc are the actual expressions for ascending and
	// descending order for this sort field.
	ExprAsc, ExprDesc string

	// Desc is true if this field should be sorted in descending order.
	Desc bool
}

Sort defines a sort field.

func (Sort) String

func (s Sort) String() string

String converts a sort field to a string. This prefers using ExprAsc and ExprDesc, then Expr with ASC or DESC suffix, then Name with ASC or DESC suffix.

type Sorts

type Sorts []*Sort

Sorts is a slice of sort fields.

func (Sorts) Search

func (ss Sorts) Search(n string) *Sort

Search returns a sort field by name or nil if not found.

func (Sorts) String

func (ss Sorts) String() string

String converts the slice into a comma-separated list as a string.

Jump to

Keyboard shortcuts

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