jsonapisdk

package module
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2018 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	IErrScopeNoValue         = errors.New("No value provided within scope.")
	IErrPresetInvalidScope   = errors.New("Pressetting invalid scope value.")
	IErrPresetNoValues       = errors.New("Preset no values")
	IErrInvalidValueType     = errors.New("Trying to preset values of invalid type.")
	IErrInvalidScopeType     = errors.New("Invalid scope type. Available values are slice of pointers to struct or pointer to struct")
	IErrValueNotValid        = errors.New("Value not valid.")
	IErrModelHandlerNotFound = errors.New("Model Handler not found.")
)
View Source
var (
	FullCRUD = []EndpointType{
		Create,
		Get,
		List,
		Patch,
		Delete,
	}

	ReadOnly = []EndpointType{
		Get,
		List,
	}

	CreateReadUpdate = []EndpointType{
		Create,
		Get,
		List,
		Patch,
	}

	CreateRead = []EndpointType{
		Create,
		Get,
		List,
	}
)
View Source
var DefaultErrorMap map[unidb.Error]jsonapi.ErrorObject = map[unidb.Error]jsonapi.ErrorObject{
	unidb.ErrNoResult:              jsonapi.ErrResourceNotFound,
	unidb.ErrConnExc:               jsonapi.ErrInternalError,
	unidb.ErrCardinalityViolation:  jsonapi.ErrInternalError,
	unidb.ErrDataException:         jsonapi.ErrInvalidInput,
	unidb.ErrIntegrConstViolation:  jsonapi.ErrInvalidInput,
	unidb.ErrRestrictViolation:     jsonapi.ErrInvalidInput,
	unidb.ErrNotNullViolation:      jsonapi.ErrInvalidInput,
	unidb.ErrForeignKeyViolation:   jsonapi.ErrInvalidInput,
	unidb.ErrUniqueViolation:       jsonapi.ErrResourceAlreadyExists,
	unidb.ErrCheckViolation:        jsonapi.ErrInvalidInput,
	unidb.ErrInvalidTransState:     jsonapi.ErrInternalError,
	unidb.ErrInvalidTransTerm:      jsonapi.ErrInternalError,
	unidb.ErrTransRollback:         jsonapi.ErrInternalError,
	unidb.ErrTxDone:                jsonapi.ErrInternalError,
	unidb.ErrInvalidAuthorization:  jsonapi.ErrInsufficientAccPerm,
	unidb.ErrInvalidPassword:       jsonapi.ErrInternalError,
	unidb.ErrInvalidSchemaName:     jsonapi.ErrInternalError,
	unidb.ErrInvalidSyntax:         jsonapi.ErrInternalError,
	unidb.ErrInsufficientPrivilege: jsonapi.ErrInsufficientAccPerm,
	unidb.ErrInsufficientResources: jsonapi.ErrInternalError,
	unidb.ErrProgramLimitExceeded:  jsonapi.ErrInternalError,
	unidb.ErrSystemError:           jsonapi.ErrInternalError,
	unidb.ErrInternalError:         jsonapi.ErrInternalError,
	unidb.ErrUnspecifiedError:      jsonapi.ErrInternalError,
}

DefaultErrorMap contain default mapping of unidb.Error prototype into jsonapi.Error. It is used by default by 'ErrorManager' if created using New() function.

View Source
var IErrInvalidModelEndpoint = errors.New("Invalid model endpoint")

Functions

func SetContentType

func SetContentType(rw http.ResponseWriter)

Types

type Endpoint

type Endpoint struct {
	Type EndpointType

	// Precheck
	Prechecks []*jsonapi.PresetPair

	// Preset
	Presets []*jsonapi.PresetPair

	// Preset default Filters
	PresetFilters []*jsonapi.FilterField

	// Preset default sorting
	PresetSort []*jsonapi.SortField

	// Preset default limit offset
	PresetPaginate *jsonapi.Pagination
}

func (*Endpoint) String added in v0.5.2

func (e *Endpoint) String() string

type EndpointType

type EndpointType int
const (
	UnkownPath EndpointType = iota
	Create
	Get
	List
	Patch
	PatchAll
	Delete
	DeleteAll
)

func (EndpointType) String added in v0.5.2

func (e EndpointType) String() string

type ErrorManager

type ErrorManager struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

ErrorManager defines the database unidb.Error one-to-one mapping into jsonapi.Error. The default error mapping is defined in package variable 'DefaultErrorMap'.

func NewDBErrorMgr

func NewDBErrorMgr() *ErrorManager

NewErrorMapper creates new error handler with already inited ErrorMap

func (*ErrorManager) Handle

func (r *ErrorManager) Handle(dberr *unidb.Error) (*jsonapi.ErrorObject, error)

Handle enables unidb.Error handling so that proper jsonapi.ErrorObject is returned. It returns jsonapi.ErrorObject if given database error exists in the private error mapping. If provided dberror doesn't have prototype or no mapping exists for given unidb.Error an application 'error' would be returned. Thread safety by using RWMutex.RLock

func (*ErrorManager) LoadCustomErrorMap

func (r *ErrorManager) LoadCustomErrorMap(errorMap map[unidb.Error]jsonapi.ErrorObject)

LoadCustomErrorMap enables replacement of the ErrorManager default error map. This operation is thread safe - with RWMutex.Lock

func (*ErrorManager) UpdateErrorEntry

func (r *ErrorManager) UpdateErrorEntry(
	dberr unidb.Error,
	apierr jsonapi.ErrorObject,
)

UpdateErrorMapEntry changes single entry in the Error Handler error map. This operation is thread safe - with RWMutex.Lock

type JSONAPIHandler

type JSONAPIHandler struct {
	// jsonapi controller
	Controller *jsonapi.Controller

	// Repositories
	DefaultRepository Repository

	// DBErrMgr database error manager
	DBErrMgr *ErrorManager

	// Supported Languages
	SupportedLanguages []language.Tag

	// LanguageMatcher matches the possible language
	LanguageMatcher language.Matcher

	// Validators validate given
	Validator *validator.Validate

	// ModelHandlers
	ModelHandlers map[reflect.Type]*ModelHandler
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(
	c *jsonapi.Controller,
	log unilogger.LeveledLogger,
	DBErrMgr *ErrorManager,
) *JSONAPIHandler

NewHandler creates new handler on the base of

func (*JSONAPIHandler) AddModelHandlers

func (h *JSONAPIHandler) AddModelHandlers(models ...*ModelHandler) error

AddModelHandlers adds the model handlers for given JSONAPI Handler. If there are handlers with the same type the funciton returns error.

func (*JSONAPIHandler) AddModelsEndpoint

func (h *JSONAPIHandler) AddModelsEndpoint(model interface{}, endpoint *Endpoint) error

AddModelsEndpoint adds the endpoint to the provided model. If the model is not set within given handler, an endpoint is already occupied or is of unknown type the function returns error.

func (*JSONAPIHandler) AddModelsPrecheckPair

func (h *JSONAPIHandler) AddModelsPrecheckPair(
	model interface{},
	precheckPair *jsonapi.PresetPair,
	endpoint EndpointType,
) error

AddModelsPrecheckPair gets the model handler from the JSONAPIHandler, and adds the precheckPair to the specific endpoint for this model. Returns error if the model is not present within JSONAPIHandler or if the model does not support given endpoint.

func (*JSONAPIHandler) AddModelsPresetPair

func (h *JSONAPIHandler) AddModelsPresetPair(
	model interface{},
	presetPair *jsonapi.PresetPair,
	endpoint EndpointType,
) error

AddModelsPresetPair gets the model handler from the JSONAPIHandler, and adds the presetpair to the specific endpoint for this model. Returns error if the model is not present within JSONAPIHandler or if the model does not support given endpoint.

func (*JSONAPIHandler) CheckPrecheckValues

func (h *JSONAPIHandler) CheckPrecheckValues(
	scope *jsonapi.Scope,
	filter *jsonapi.FilterField,
) (err error)

func (*JSONAPIHandler) CheckValueLanguage

func (h *JSONAPIHandler) CheckValueLanguage(
	scope *jsonapi.Scope,
	rw http.ResponseWriter,
) (langtag language.Tag, ok bool)

CheckLanguage checks the language value within given scope's Value. It parses the field's value into language.Tag, and if no matching language is provided or the // language is not supported, it writes error to the response.

func (*JSONAPIHandler) Create

func (h *JSONAPIHandler) Create(model *ModelHandler) http.HandlerFunc

Create returns http.HandlerFunc that creates new 'model' entity within it's repository.

I18n It supports i18n of the model. The language in the request is being checked if the value provided is supported by the server. If the match is confident the language is converted.

Correctly Response with status '201' Created.

func (*JSONAPIHandler) Delete

func (h *JSONAPIHandler) Delete(model *ModelHandler) http.HandlerFunc

func (*JSONAPIHandler) DisplaySupportedLanguages

func (h *JSONAPIHandler) DisplaySupportedLanguages() []string

func (*JSONAPIHandler) EndpointForbidden added in v0.5.2

func (h *JSONAPIHandler) EndpointForbidden(
	model *ModelHandler,
	endpoint EndpointType,
) http.HandlerFunc

func (*JSONAPIHandler) Get

Get returns a http.HandlerFunc that gets single entity from the "model's" repository.

func (*JSONAPIHandler) GetIncluded

func (h *JSONAPIHandler) GetIncluded(
	scope *jsonapi.Scope,
	rw http.ResponseWriter,
	req *http.Request,
	tag language.Tag,
) (correct bool)

Exported method to get included values for given scope

func (*JSONAPIHandler) GetLanguage

func (h *JSONAPIHandler) GetLanguage(
	req *http.Request,
	rw http.ResponseWriter,
) (tag language.Tag, ok bool)

func (*JSONAPIHandler) GetModelHandler

func (h *JSONAPIHandler) GetModelHandler(model interface{}) (mHandler *ModelHandler, err error)

GetModelHandler gets the model handler that matches the provided model type. If no handler is found within JSONAPIHandler the function returns an error.

func (*JSONAPIHandler) GetPresetValues

func (h *JSONAPIHandler) GetPresetValues(
	presetScope *jsonapi.Scope,
	filter *jsonapi.FilterField,
	rw http.ResponseWriter,
) (values []interface{}, ok bool)

GetPresetValues gets the values from the presetScope

func (*JSONAPIHandler) GetRelated

func (h *JSONAPIHandler) GetRelated(root *ModelHandler) http.HandlerFunc

GetRelated returns a http.HandlerFunc that returns the related field for the 'root' model It prepares the scope rooted with 'root' model with some id and gets the 'related' field from url. Related field must be a relationship, otherwise an error would be returned. The handler gets the root and the specific related field 'id' from the repository and then gets the related object from it's repository. If no error occurred an jsonapi related object is being returned

func (*JSONAPIHandler) GetRelationship

func (h *JSONAPIHandler) GetRelationship(root *ModelHandler) http.HandlerFunc

GetRelationship returns a http.HandlerFunc that returns in the response the relationship field for the root model

func (*JSONAPIHandler) GetRepositoryByType

func (h *JSONAPIHandler) GetRepositoryByType(model reflect.Type) (repo Repository)

GetRepositoryByType returns the repository by provided model type. If no modelHandler is found within the jsonapi handler - then the default repository would be set.

func (*JSONAPIHandler) HandleValidateError

func (h *JSONAPIHandler) HandleValidateError(
	model *ModelHandler,
	err error,
	rw http.ResponseWriter,
)

func (*JSONAPIHandler) HeaderContentLanguage

func (h *JSONAPIHandler) HeaderContentLanguage(rw http.ResponseWriter, langtag language.Tag)

HeaderContentLanguage sets the response Header 'Content-Language' to the lang tag provided in argument.

func (*JSONAPIHandler) List

func (h *JSONAPIHandler) List(model *ModelHandler) http.HandlerFunc

List returns a http.HandlerFunc that response with the model's entities taken from it's repository. QueryParameters:

func (*JSONAPIHandler) MarshalErrors

func (h *JSONAPIHandler) MarshalErrors(rw http.ResponseWriter, errors ...*jsonapi.ErrorObject)

func (*JSONAPIHandler) MarshalInternalError

func (h *JSONAPIHandler) MarshalInternalError(rw http.ResponseWriter)

func (*JSONAPIHandler) MarshalScope

func (h *JSONAPIHandler) MarshalScope(
	scope *jsonapi.Scope,
	rw http.ResponseWriter,
	req *http.Request,
)

MarshalScope is a handler helper for marshaling the provided scope.

func (*JSONAPIHandler) Patch

func (h *JSONAPIHandler) Patch(model *ModelHandler) http.HandlerFunc

Patch the patch endpoint is used to patch given entity. It accepts only the models that matches the provided model Handler. If the incoming model PRESETTING:

  • Preset values using PresetScope
  • Precheck values using PrecheckScope

func (*JSONAPIHandler) PresetScopeValue

func (h *JSONAPIHandler) PresetScopeValue(
	scope *jsonapi.Scope,
	fieldFilter *jsonapi.FilterField,
	values ...interface{},
) (err error)

PresetScopeValue presets provided values for given scope. The fieldFilter points where the value should be set within given scope. The scope value should not be nil

func (*JSONAPIHandler) ReplaceModelsEndpoint

func (h *JSONAPIHandler) ReplaceModelsEndpoint(model interface{}, endpoint *Endpoint) error

ReplaceModelsEndpoint replaces an endpoint for provided model. If the model is not set within JSONAPIHandler or an endpoint is of unknown type the function returns an error.

func (*JSONAPIHandler) SetDefaultRepo

func (h *JSONAPIHandler) SetDefaultRepo(Repositoriesitory Repository)

func (*JSONAPIHandler) SetLanguages

func (h *JSONAPIHandler) SetLanguages(languages ...language.Tag)

SetLanguages sets the default langauges for given handler. Creates the language matcher for given languages.

func (*JSONAPIHandler) SetPresetFilterValues

func (h *JSONAPIHandler) SetPresetFilterValues(
	filter *jsonapi.FilterField,
	values ...interface{},
) error

SetPresetValues sets provided values for given filterfield. If the filterfield does not contain values or subfield values the function returns error.

func (*JSONAPIHandler) UnmarshalScope

func (h *JSONAPIHandler) UnmarshalScope(
	model reflect.Type,
	rw http.ResponseWriter,
	req *http.Request,
) *jsonapi.Scope

type ModelHandler

type ModelHandler struct {
	ModelType reflect.Type

	// Endpoints contains preset information about the provided model.
	Create *Endpoint
	Get    *Endpoint
	List   *Endpoint
	Patch  *Endpoint
	Delete *Endpoint

	// Repository defines the repository for the provided model
	Repository Repository
}

ModelHandler defines how the

func NewModelHandler

func NewModelHandler(
	model interface{},
	repository Repository,
	endpoints []EndpointType,
) (m *ModelHandler, err error)

NewModelHandler creates new model handler for given model, with provided repository and with support for provided endpoints. Returns an error if provided model is not a struct or a ptr to struct or if the endpoint is of unknown type.

func (*ModelHandler) AddEndpoint

func (m *ModelHandler) AddEndpoint(endpoint *Endpoint) error

AddEndpoint adds the endpoint to the provided model handler. If the endpoint is of unknown type or the handler already contains given endpoint an error would be returned.

func (*ModelHandler) AddOffsetPresetPaginate

func (m *ModelHandler) AddOffsetPresetPaginate(
	limit, offset int,
	endpointTypes []EndpointType,
) error

func (*ModelHandler) AddPrecheckPair

func (m *ModelHandler) AddPrecheckPair(
	precheckPair *jsonapi.PresetPair,
	endpoint EndpointType,
) error

AddPrecheckPair adds the precheck pair to the given model on provided endpoint. If the endpoint was not set or is unknown the function returns error.

func (*ModelHandler) AddPresetFilter

func (m *ModelHandler) AddPresetFilter(
	fieldName string,
	endpointTypes []EndpointType,
	operator jsonapi.FilterOperator,
	values ...interface{},
) error

func (*ModelHandler) AddPresetPair

func (m *ModelHandler) AddPresetPair(
	presetPair *jsonapi.PresetPair,
	endpoint EndpointType,
) error

AddPresetScope adds preset scope to provided endpoint. If the endpoint was not set or is unknown the function returns error.

func (*ModelHandler) AddPresetSort

func (m *ModelHandler) AddPresetSort(
	fieldName string,
	endpointTypes []EndpointType,
	order jsonapi.Order,
) error

func (*ModelHandler) ReplaceEndpoint

func (m *ModelHandler) ReplaceEndpoint(endpoint *Endpoint) error

ReplaceEndpoint replaces the endpoint for the provided model handler. If the endpoint is of unknown type the function returns an error.

type Repository

type Repository interface {
	Create(scope *jsonapi.Scope) *unidb.Error
	Get(scope *jsonapi.Scope) *unidb.Error
	List(scope *jsonapi.Scope) *unidb.Error
	Patch(scope *jsonapi.Scope) *unidb.Error
	Delete(scope *jsonapi.Scope) *unidb.Error
}

Repository is an interface that specifies

Directories

Path Synopsis
repositories
routers
gin

Jump to

Keyboard shortcuts

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