schema

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2018 License: Apache-2.0 Imports: 20 Imported by: 50

Documentation

Index

Constants

View Source
const (
	Unique   IndexType = "UNIQUE"
	FullText           = "FULLTEXT"
	Spatial            = "SPATIAL"
	None               = ""
)

Index types Unique, FullText, Spatial, None

View Source
const (
	// ActionGlob allows to perform all actions
	ActionGlob = "*"
	// ActionCreate allows to create a resource
	ActionCreate = "create"
	// ActionRead allows to list resources and show details
	ActionRead = "read"
	// ActionUpdate allows to update a resource
	ActionUpdate = "update"
	// ActionDelete allows to delete a resource
	ActionDelete = "delete"
	// ActionAttach allows a resource to have a relation to another resource
	ActionAttach = "__attach__"
)
View Source
const (
	All filterType = iota
	Visible
	Hidden
	Invalid
)

Variables

AllActions are all possible actions

View Source
var DefaultExtension = "javascript"

DefaultExtension configuration

Functions

func ClearManager

func ClearManager()

ClearManager clears manager

func FormatParentID

func FormatParentID(parent string) string

FormatParentID ...

func PolicyValidate

func PolicyValidate(action, path string, auth Authorization, policies []*Policy) (foundPolicy *Policy, foundRole *Role)

PolicyValidate validates api request using policy validation

func SortActions

func SortActions(schema *Schema)

SortActions sort actions by id

Types

type Action

type Action struct {
	ID           string
	Method       string
	Path         string
	Description  string
	InputSchema  map[string]interface{}
	OutputSchema map[string]interface{}
	Parameters   map[string]interface{}
}

Action struct

func NewAction

func NewAction(id, method, path, description string, inputSchema, outputSchema, parameters map[string]interface{}) Action

NewAction create Action

func NewActionFromObject

func NewActionFromObject(id string, rawData interface{}) (Action, error)

NewActionFromObject create Action object from json

func (*Action) GetInputParameterNames

func (action *Action) GetInputParameterNames() ([]string, error)

GetInputParameterNames gets action input parameter names

func (*Action) GetInputParameterType

func (action *Action) GetInputParameterType(parameter string) (string, error)

GetInputParameterType gets input parameter type

func (*Action) GetInputType

func (action *Action) GetInputType() (string, error)

GetInputType gets action input type

func (*Action) TakesID

func (action *Action) TakesID() bool

TakesID checks if action takes ID as a parameter

func (*Action) TakesNoArgs

func (action *Action) TakesNoArgs() bool

TakesNoArgs checks if action takes no arguments

type AttachInfo

type AttachInfo struct {
	SchemaID               string
	OtherResourceCondition *ResourceCondition
	RelationPropertyName   string
}

Additional information for the "attach" action

type Authorization

type Authorization interface {
	TenantID() string
	TenantName() string
	AuthToken() string
	Roles() []*Role
	Catalog() []*Catalog
}

Authorization interface

func NewAuthorization

func NewAuthorization(tenantID, tenantName, authToken string, roleIDs []string, catalog []*Catalog) Authorization

NewAuthorization is a constructor for auth info

type BaseAuthorization

type BaseAuthorization struct {
	// contains filtered or unexported fields
}

BaseAuthorization is base struct for Authorization

func (*BaseAuthorization) AuthToken

func (auth *BaseAuthorization) AuthToken() string

AuthToken returns X_AUTH_TOKEN

func (*BaseAuthorization) Catalog

func (auth *BaseAuthorization) Catalog() []*Catalog

Catalog returns service catalog

func (*BaseAuthorization) Roles

func (auth *BaseAuthorization) Roles() []*Role

Roles returns authorized roles

func (*BaseAuthorization) TenantID

func (auth *BaseAuthorization) TenantID() string

TenantID returns authorized tenant

func (*BaseAuthorization) TenantName

func (auth *BaseAuthorization) TenantName() string

TenantName returns authorized tenant name

type Catalog

type Catalog struct {
	Name      string
	Type      string
	Endpoints []*Endpoint
}

Catalog represents service catalog info

func NewCatalog

func NewCatalog(name, catalogType string, endPoints []*Endpoint) *Catalog

NewCatalog initializes Catalog

type Endpoint

type Endpoint struct {
	URL       string
	Region    string
	Interface string
}

Endpoint represents Endpoint information

func NewEndpoint

func NewEndpoint(url, region, iface string) *Endpoint

NewEndpoint initializes Endpoint

type EventTimeLimit

type EventTimeLimit struct {
	EventRegex   *regexp.Regexp
	TimeDuration time.Duration
}

EventTimeLimit is a configuration for

time limits for a regex event

func NewEventTimeLimit

func NewEventTimeLimit(eventRegex *regexp.Regexp, timeLimit time.Duration) *EventTimeLimit

NewEventTimeLimit is a constructor for EventTimeLimit

func (*EventTimeLimit) Match

func (eventTimeLimit *EventTimeLimit) Match(event string) bool

Match checks if this path matches for extension

type Extension

type Extension struct {
	ID, CodeType, URL, File string
	Code                    string
	Path                    *regexp.Regexp
}

Extension is a small plugin for gohan

func NewExtension

func NewExtension(raw interface{}) (*Extension, error)

NewExtension returns new extension from object

func (*Extension) Match

func (e *Extension) Match(path string) bool

Match checks if this path matches for extension

type Filter

type Filter struct {
	// contains filtered or unexported fields
}

func CreateExcludeAllFilter

func CreateExcludeAllFilter() *Filter

func (*Filter) IsForbidden

func (f *Filter) IsForbidden(key string) bool

func (*Filter) RemoveHiddenKeysFromMap

func (f *Filter) RemoveHiddenKeysFromMap(data map[string]interface{}) map[string]interface{}

func (*Filter) RemoveHiddenKeysFromSlice

func (f *Filter) RemoveHiddenKeysFromSlice(data []string) []string

type FilterFactory

type FilterFactory struct {
	// contains filtered or unexported fields
}

func (*FilterFactory) CreateFilterFromProperties

func (f *FilterFactory) CreateFilterFromProperties(visible, hidden []string) (*Filter, error)

type Index

type Index struct {
	Name    string
	Columns []string
	Type    IndexType
}

Index is a definition of each Index

func NewIndex

func NewIndex(name string, columns []string, indexType IndexType) Index

NewIndex is a constructor for Index type

func NewIndexFromObj

func NewIndexFromObj(name string, rawTypeData interface{}) (*Index, error)

NewIndexFromObj make Index from obj

type IndexType

type IndexType string

IndexType type of index

type Link struct {
	Href string `json:"href"`
	Rel  string `json:"rel"`
}

Link ...

type LockPolicy

type LockPolicy int

LockPolicy is type lock policy

const (
	LockRelatedResources LockPolicy = iota
	SkipRelatedResources
	NoLocking
)

LockRelatedResources is type of LockPolicy

type Manager

type Manager struct {
	Extensions []*Extension
	TimeLimit  time.Duration         // default time limit for an extension
	TimeLimits []*PathEventTimeLimit // a list of exceptions for time limits
	// contains filtered or unexported fields
}

Manager manages handling of schemas Manager manages routing with external data and gohan resource representation This is a singleton class

func GetManager

func GetManager() *Manager

GetManager get manager

func (*Manager) ClearExtensions

func (manager *Manager) ClearExtensions()

ClearExtensions clears extensions

func (*Manager) GetAttachmentPolicies

func (manager *Manager) GetAttachmentPolicies(path string, auth Authorization) []*Policy

GetAttachmentPolicies returns policies that will validate relations (attachments)

func (*Manager) LoadExtensions

func (manager *Manager) LoadExtensions(extensions []*Resource) error

LoadExtensions register extension by db object

func (*Manager) LoadNamespaces

func (manager *Manager) LoadNamespaces(namespaces []*Resource) error

LoadNamespaces register namespaces by db object

func (*Manager) LoadPolicies

func (manager *Manager) LoadPolicies(policies []*Resource) error

LoadPolicies register policy by db object

func (*Manager) LoadResource

func (manager *Manager) LoadResource(schemaID string, dataMap map[string]interface{}) (*Resource, error)

LoadResource makes resource from datamap

func (*Manager) LoadResourceFromJSONString

func (manager *Manager) LoadResourceFromJSONString(schemaID string, jsonData string) (*Resource, error)

LoadResourceFromJSONString makes resource from jsonString

func (*Manager) LoadSchemaFromFile

func (manager *Manager) LoadSchemaFromFile(filePath string) error

LoadSchemaFromFile loads schema from json file

func (*Manager) LoadSchemasFromFiles

func (manager *Manager) LoadSchemasFromFiles(filePaths ...string) error

LoadSchemasFromFiles calls LoadSchemaFromFile for each of provided filePaths

func (*Manager) Namespace

func (manager *Manager) Namespace(name string) (*Namespace, bool)

Namespace gets namespace from manager

func (*Manager) Namespaces

func (manager *Manager) Namespaces() map[string]*Namespace

Namespaces gets namespaces from manager

func (*Manager) NobodyResourcePaths

func (manager *Manager) NobodyResourcePaths() []*regexp.Regexp

NobodyResourcePaths returns a list of paths that do not require authorization

func (*Manager) OrderedLoadSchemasFromFiles

func (manager *Manager) OrderedLoadSchemasFromFiles(filePaths []string) error

OrderedLoadSchemasFromFiles calls LoadSchemaFromFile for each file in right order - first abstract then parent and rest on the end

func (*Manager) OrderedSchemas

func (manager *Manager) OrderedSchemas() []*Schema

OrderedSchemas gets schema from manager ordered

func (*Manager) Policies

func (manager *Manager) Policies() []*Policy

Policies gets policies from manager

func (*Manager) PolicyValidate

func (manager *Manager) PolicyValidate(action, path string, auth Authorization) (*Policy, *Role)

PolicyValidate API request using policy statements

func (*Manager) Schema

func (manager *Manager) Schema(id string) (*Schema, bool)

Schema gets schema from manager

func (*Manager) Schemas

func (manager *Manager) Schemas() Map

Schemas gets schema from manager

func (*Manager) String

func (manager *Manager) String() string

func (*Manager) UnRegisterSchema

func (manager *Manager) UnRegisterSchema(schema *Schema) error

UnRegisterSchema unregister schema

func (*Manager) ValidateSchema

func (manager *Manager) ValidateSchema(schemaPath, filePath string) error

ValidateSchema validates json schema

type Map

type Map map[string]*Schema

Map is a map of schema

type Namespace

type Namespace struct {
	ID              string
	Parent          string
	ParentNamespace *Namespace
	Prefix          string
}

Namespace describes a group of schemas that form a common endpoint

func NewNamespace

func NewNamespace(raw interface{}) (*Namespace, error)

NewNamespace is a constructor for a namespace

func (*Namespace) GetFullPrefix

func (namespace *Namespace) GetFullPrefix() string

GetFullPrefix returns a full prefix of a namespace

func (*Namespace) IsTopLevel

func (namespace *Namespace) IsTopLevel() bool

IsTopLevel checks whether namespace is a top-level namespace

func (*Namespace) SetParentNamespace

func (namespace *Namespace) SetParentNamespace(parent *Namespace)

SetParentNamespace sets a parent of a namespace to the provided one

type NamespaceResource

type NamespaceResource struct {
	Links      []Link `json:"links"`
	Name       string `json:"name"`
	Collection string `json:"collection"`
}

NamespaceResource ...

type PathEventTimeLimit

type PathEventTimeLimit struct {
	PathRegex    *regexp.Regexp
	EventRegex   *regexp.Regexp
	TimeDuration time.Duration
}

PathEventTimeLimit is a configuration for

time limits for a regex path and a regex event

func NewPathEventTimeLimit

func NewPathEventTimeLimit(pathRegex, eventRegex string, timeDuration time.Duration) *PathEventTimeLimit

NewPathEventTimeLimit is a constructor for PathEventTimeLimit

func (*PathEventTimeLimit) Match

func (pathEventTimeLimit *PathEventTimeLimit) Match(path string) bool

Match checks if this path matches for extension

type Policy

type Policy struct {
	ID, Description, Principal, Action, Effect string
	RawData                                    interface{}
	// contains filtered or unexported fields
}

Policy describes policy configuration for APIs

func GetAttachmentPolicies

func GetAttachmentPolicies(path string, auth Authorization, policies []*Policy) []*Policy

func NewEmptyPolicy

func NewEmptyPolicy() *Policy

NewEmptyPolicy Return Empty policy which match everything

func NewPolicy

func NewPolicy(raw interface{}) (*Policy, error)

NewPolicy returns new policy from object

func (*Policy) Check

func (p *Policy) Check(action string, authorization Authorization, data map[string]interface{}) error

Checks if user is authorized to perform given action

func (*Policy) FilterSchema

func (p *Policy) FilterSchema(
	properties map[string]interface{},
	propertiesOrder, required []string,
) (map[string]interface{}, []string, []string)

FilterSchema filters properties in the schema itself

func (*Policy) GetCurrentResourceCondition

func (p *Policy) GetCurrentResourceCondition() *ResourceCondition

func (*Policy) GetOtherResourceCondition

func (policy *Policy) GetOtherResourceCondition() *ResourceCondition

func (*Policy) GetPropertyFilter

func (policy *Policy) GetPropertyFilter() *Filter

func (*Policy) GetRelationPropertyName

func (policy *Policy) GetRelationPropertyName() string

func (*Policy) GetResourcePathRegexp

func (policy *Policy) GetResourcePathRegexp() *regexp.Regexp

func (*Policy) IsDeny

func (p *Policy) IsDeny() bool

func (*Policy) RemoveHiddenProperty

func (p *Policy) RemoveHiddenProperty(data map[string]interface{}) map[string]interface{}

RemoveHiddenProperty removes hidden data from data by Policy This method returns nil if all data get filtered out

type Predicate

type Predicate interface {
	Validate(string) bool
}

type Property

type Property struct {
	ID, Title, Description string
	Type, Format           string
	Properties             map[string]interface{}
	Relation               string
	RelationColumn         string
	RelationProperty       string
	Unique                 bool
	Nullable               bool
	SQLType                string
	OnDeleteCascade        bool
	Default                interface{}
	Indexed                bool
}

Property is a definition of each Property

func NewProperty

func NewProperty(id, title, description, typeID, format, relation, relationColumn, relationProperty, sqlType string, unique, nullable, onDeleteCascade bool, properties map[string]interface{}, defaultValue interface{}, indexed bool) Property

NewProperty is a constructor for Property type

func NewPropertyFromObj

func NewPropertyFromObj(id string, rawTypeData interface{}, required bool) *Property

NewPropertyFromObj make Property from obj

type PropertyMap

type PropertyMap map[string]Property

PropertyMap is a map of Property

type PropertyOrder

type PropertyOrder struct {
	// contains filtered or unexported fields
}

PropertyOrder is type of property order

func (PropertyOrder) Len

func (p PropertyOrder) Len() int

func (PropertyOrder) Less

func (p PropertyOrder) Less(i, j int) bool

func (PropertyOrder) String

func (p PropertyOrder) String() string

func (PropertyOrder) Swap

func (p PropertyOrder) Swap(i, j int)

type Resource

type Resource struct {
	// contains filtered or unexported fields
}

Resource is a instance of resource

func NewResource

func NewResource(schema *Schema, properties map[string]interface{}) (*Resource, error)

NewResource is a constructor for a resource

func (*Resource) Data

func (resource *Resource) Data() map[string]interface{}

Data gets data from resource

func (*Resource) Get

func (resource *Resource) Get(key string) interface{}

Get gets property from resource

func (*Resource) ID

func (resource *Resource) ID() string

ID gets id from resource

func (*Resource) JSONString

func (resource *Resource) JSONString() (string, error)

JSONString returns json string of the resource

func (*Resource) ParentID

func (resource *Resource) ParentID() string

ParentID get parent id of the resource

func (*Resource) Path

func (resource *Resource) Path() string

Path generate path for this resource

func (*Resource) PopulateDefaults

func (resource *Resource) PopulateDefaults() error

PopulateDefaults Populates not provided data with defaults

func (*Resource) Schema

func (resource *Resource) Schema() *Schema

Schema gets schema from resource

func (*Resource) SetParentID

func (resource *Resource) SetParentID(id string)

SetParentID set parent id of the resource

func (*Resource) String

func (resource *Resource) String() string

String return string form representation

func (*Resource) Update

func (resource *Resource) Update(updateData map[string]interface{}) error

Update resource data

func (*Resource) Values

func (resource *Resource) Values() []interface{}

Values returns list of values

type ResourceCondition

type ResourceCondition struct {
	Condition []interface{}
	// contains filtered or unexported fields
}

func NewResourceCondition

func NewResourceCondition(rawCondition []interface{}, policyID string) (*ResourceCondition, error)

func (*ResourceCondition) AddCustomFilters

func (policy *ResourceCondition) AddCustomFilters(filters map[string]interface{}, tenantId string)

Adds custom filters based on this policy to the `filters` map

func (*ResourceCondition) ApplyPropertyConditionFilter

func (p *ResourceCondition) ApplyPropertyConditionFilter(action string, data map[string]interface{}, updateCandidateData map[string]interface{}) error

ApplyPropertyConditionFilter applies filter based on Property You need to pass candidate update value in updateCandidateData on update API, so that we can limit allowed update value. Let's say we would like to only allow to update from ACTIVE to ERROR on an API. We can define this policy like this.

  • action: 'update' condition:
  • property: status: ACTIVE: ERROR effect: allow id: member principal: Member

This policy check error in case of followings - Original value isn't ACTIVE - Update candidate value isn't ERROR

func (*ResourceCondition) GetTenantIDFilter

func (p *ResourceCondition) GetTenantIDFilter(action string, tenantID string) []string

GetTenantIDFilter returns tenants filter for the action performed by the tenant

func (*ResourceCondition) RequireOwner

func (p *ResourceCondition) RequireOwner() bool

RequireOwner ...

type Role

type Role struct {
	Name string
}

Role describes user role

func (*Role) Match

func (r *Role) Match(principal string) bool

Match checks if this role is for this principal

type Schema

type Schema struct {
	ID, Plural, Title, Description string
	Type                           string
	Extends                        []string
	ParentSchema                   *Schema
	Parent                         string
	NamespaceID                    string
	Namespace                      *Namespace
	Metadata                       map[string]interface{}
	Prefix                         string
	Properties                     []Property
	Indexes                        []Index
	JSONSchema                     map[string]interface{}
	JSONSchemaOnCreate             map[string]interface{}
	JSONSchemaOnUpdate             map[string]interface{}
	Actions                        []Action
	Singular                       string
	URL                            string
	URLWithParents                 string
	RawData                        interface{}
	IsolationLevel                 map[string]interface{}
	OnParentDeleteCascade          bool
	OrderPropertiesBefore          []string
}

Schema type for defining data type

func GetSchemaByPath

func GetSchemaByPath(path string) *Schema

GetSchemaByPath - gets schema by sync_key_template path

func GetSchemaByURLPath

func GetSchemaByURLPath(path string) *Schema

GetSchemaByURLPath - gets schema by resource path (from API)

func NewSchema

func NewSchema(id, plural, title, description, singular string) *Schema

NewSchema is a constructor for a schema

func NewSchemaFromObj

func NewSchemaFromObj(rawTypeData interface{}) (*Schema, error)

NewSchemaFromObj is a constructor for a schema by obj

func (*Schema) Extend

func (schema *Schema) Extend(fromSchema *Schema) error

Extend extends target schema

func (*Schema) GenerateCustomPath

func (schema *Schema) GenerateCustomPath(data map[string]interface{}) (path string, err error)

GenerateCustomPath - returns custom path based on sync_key_template

func (*Schema) GetActionFromCommand

func (schema *Schema) GetActionFromCommand(command string) *Action

GetActionFromCommand gets action with given id

func (*Schema) GetActionURL

func (schema *Schema) GetActionURL(path string) string

GetActionURL returns a URL for access to resources actions

func (*Schema) GetActionURLWithParents

func (schema *Schema) GetActionURLWithParents(path string) string

GetActionURLWithParents returns a URL for access to resources actions with parent suffix

func (*Schema) GetDbTableName

func (schema *Schema) GetDbTableName() string

GetDbTableName returns a name of DB table used for storing schema instances

func (*Schema) GetLockingPolicy

func (schema *Schema) GetLockingPolicy(event string) LockPolicy

GetLockingPolicy gets locking policy for given schema and event

func (*Schema) GetParentURL

func (schema *Schema) GetParentURL() string

GetParentURL returns Parent URL

func (*Schema) GetPluralURL

func (schema *Schema) GetPluralURL() string

GetPluralURL returns a URL for access to all schema objects

func (*Schema) GetPluralURLWithParents

func (schema *Schema) GetPluralURLWithParents() string

GetPluralURLWithParents returns a URL for access to all schema objects

func (*Schema) GetPropertyByID

func (schema *Schema) GetPropertyByID(id string) (*Property, error)

GetPropertyByID get a property object using ID

func (*Schema) GetResourceIDFromPath

func (schema *Schema) GetResourceIDFromPath(schemaPath string) string

GetResourceIDFromPath - parse path and gets resourceID from it

func (*Schema) GetSingleURL

func (schema *Schema) GetSingleURL() string

GetSingleURL returns a URL for access to a single schema object

func (*Schema) GetSingleURLWithParents

func (schema *Schema) GetSingleURLWithParents() string

GetSingleURLWithParents returns a URL for access to a single schema object

func (*Schema) Init

func (schema *Schema) Init() error

Init initializes schema

func (*Schema) IsAbstract

func (schema *Schema) IsAbstract() bool

IsAbstract checks if this schema is abstract or not

func (*Schema) JSON

func (schema *Schema) JSON() map[string]interface{}

JSON returns json format of schema

func (*Schema) ParentID

func (schema *Schema) ParentID() string

ParentID returns parent property ID

func (*Schema) ParentSchemaPropertyID

func (schema *Schema) ParentSchemaPropertyID() string

ParentSchemaPropertyID get property id for parent relation

func (*Schema) SetNamespace

func (schema *Schema) SetNamespace(namespace *Namespace)

SetNamespace sets namespace

func (*Schema) SetParentSchema

func (schema *Schema) SetParentSchema(parentSchema *Schema)

SetParentSchema sets parent schema

func (*Schema) SkipConfigPrefix

func (schema *Schema) SkipConfigPrefix() bool

SkipConfigPrefix - whether to skip /config/ prefix to pushed paths, defaults to false

func (*Schema) StateVersioning

func (schema *Schema) StateVersioning() bool

StateVersioning whether resources created from this schema should track state and config versions

func (*Schema) SyncKeyTemplate

func (schema *Schema) SyncKeyTemplate() (syncKeyTemplate string, ok bool)

SyncKeyTemplate - for custom paths in etcd

func (*Schema) Titles

func (schema *Schema) Titles() []string

Titles returns list of Titles

func (*Schema) Validate

func (schema *Schema) Validate(jsonSchema interface{}, object interface{}) error

Validate validates json object using jsoncschema

func (*Schema) ValidateOnCreate

func (schema *Schema) ValidateOnCreate(object interface{}) error

ValidateOnCreate validates json object using jsoncschema on object creation

func (*Schema) ValidateOnUpdate

func (schema *Schema) ValidateOnUpdate(object interface{}) error

ValidateOnUpdate validates json object using jsoncschema on object update

type Schemas

type Schemas struct {
	Schemas []*Schema
}

Schemas is a list of schema This struct is needed for json decode

type Tags

type Tags map[string]string // Tags for each resource

Tags are additional metadata for resources

type Version

type Version struct {
	Status string `json:"status"`
	ID     string `json:"id"`
	Links  []Link `json:"links"`
}

Version ...

Jump to

Keyboard shortcuts

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