aphgrpc

package
v0.0.0-...-9ff59ee Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2019 License: BSD-3-Clause Imports: 26 Imported by: 3

Documentation

Overview

Package aphgrpc provides various interfaces, functions, types for building and working with gRPC services.

Index

Constants

View Source
const (
	DefaultPagenum  int64 = 1
	DefaultPagesize int64 = 10
)
View Source
const (
	// MetaKey is the key used for storing all metadata
	MetaKey = "error"
)

Variables

View Source
var (
	//ErrDatabaseQuery represents database query related errors
	ErrDatabaseQuery = newError("Database query error")
	//ErrDatabaseInsert represents database insert related errors
	ErrDatabaseInsert = newError("Database insert error")
	//ErrDatabaseUpdate represents database update related errors
	ErrDatabaseUpdate = newError("Database update error")
	//ErrDatabaseDelete represents database update delete errors
	ErrDatabaseDelete = newError("Database delete error")
	//ErrNotFound represents the absence of an HTTP resource
	ErrNotFound = newError("Resource not found")
	//ErrExists represents the presence of an HTTP resource
	ErrExists = newError("Resource already exists")
	//ErrJSONEncoding represents any json encoding error
	ErrJSONEncoding = newError("Json encoding error")
	//ErrStructMarshal represents any error with marshalling structure
	ErrStructMarshal = newError("Structure marshalling error")
	//ErrIncludeParam represents any error with invalid include query parameter
	ErrIncludeParam = newErrorWithParam("Invalid include query parameter", "include")
	//ErrSparseFieldSets represents any error with invalid sparse fieldsets query parameter
	ErrFields = newErrorWithParam("Invalid field query parameter", "field")
	//ErrFilterParam represents any error with invalid filter query paramter
	ErrFilterParam = newErrorWithParam("Invalid filter query parameter", "filter")
	//ErrNotAcceptable represents any error with wrong or inappropriate http Accept header
	ErrNotAcceptable = newError("Accept header is not acceptable")
	//ErrUnsupportedMedia represents any error with unsupported media type in http header
	ErrUnsupportedMedia = newError("Media type is not supported")
	//ErrInValidParam represents any error with validating input parameters
	ErrInValidParam = newError("Invalid parameters")
	//ErrRetrieveMetadata represents any error to retrieve grpc metadata from the running context
	ErrRetrieveMetadata = errors.New("unable to retrieve metadata")
	//ErrXForwardedHost represents any failure or absence of x-forwarded-host HTTP header in the grpc context
	ErrXForwardedHost = errors.New("x-forwarded-host header is absent")
)
View Source
var (
	ContextKeyParams  = contextKey("params")
	ContextKeyInclude = contextKey("includeStr")
	ContextKeyFilter  = contextKey("filterStr")
	ContextKeyFields  = contextKey("fieldsStr")
	ContextKeyIsList  = contextKey("isListMethod")
)

Functions

func AppendPaginationParams

func AppendPaginationParams(url string, pagenum, pagesize int64) string

func AssignFieldsToStructs

func AssignFieldsToStructs(from interface{}, to interface{})

AssignFieldsToStructs copy fields value between structure

func CheckNoRows

func CheckNoRows(err error) bool

func CustomHTTPError

func CustomHTTPError(ctx context.Context, _ *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, _ *http.Request, err error)

CustomHTTPError is a custom error handler for grpc-gateway to generate JSONAPI formatted HTTP response.

func FilterToBindValue

func FilterToBindValue(filters []*APIFilter) []interface{}

FilterToBindValue generates a postgresql compatible query expression from the given filters

func FilterToWhereClause

func FilterToWhereClause(s JSONAPIParamsInfo, filters []*APIFilter) string

FilterToWhereClause generates a postgresql compatible where clause from the provided filters

func GenBaseLink(rs JSONAPIResource) string
func GenMultiResourceLink(rs JSONAPIResource) string
func GenPaginatedLinks(url string, lastpage, pagenum, pagesize int64) map[string]string

GenPaginatedLinks generates paginated resource links from various page properties.

func GenPaginatedResourceLink(rs JSONAPIResource, pagenum, pagesize int64) string
func GenRelatedRelationshipLink(rs JSONAPIResource, rel string, id int64) string
func GenSelfRelationshipLink(rs JSONAPIResource, rel string, id int64) string
func GenSingleResourceLink(rs JSONAPIResource, id int64) string

func GetDefinedTags

func GetDefinedTags(i interface{}, tag string) []string

GetDefinedTags check for fields that are initialized and returns a slice of their matching tag values

func GetDefinedTagsWithValue

func GetDefinedTagsWithValue(i interface{}, key string) map[string]interface{}

GetDefinedTagsWithValue check for fields that are initialized and returns a map with the tag and their values

func GetReqCtx

func GetReqCtx(params *JSONAPIParams, r *jsonapi.GetRequest) context.Context

GetReqCtx generate a context data from get request

func GetTotalPageNum

func GetTotalPageNum(record, pagesize int64) int64

GetTotalPageNum calculate total no of pages from total no. records and page size

func HandleCreateResponse

func HandleCreateResponse(ctx context.Context, w http.ResponseWriter, resp proto.Message) error

HandleCreateResponse modifies the grpc gateway filter which adds the JSON API header and modifies the http status response for POST request

func HandleDeleteError

func HandleDeleteError(ctx context.Context, err error) error

func HandleError

func HandleError(ctx context.Context, err error) error

func HandleExistError

func HandleExistError(ctx context.Context, err error) error

func HandleFilterParamError

func HandleFilterParamError(ctx context.Context, err error) error

func HandleGenericError

func HandleGenericError(ctx context.Context, err error) error

func HandleGetArgError

func HandleGetArgError(ctx context.Context, err error) error

func HandleGetError

func HandleGetError(ctx context.Context, err error) error

func HandleInsertArgError

func HandleInsertArgError(ctx context.Context, err error) error

func HandleInsertError

func HandleInsertError(ctx context.Context, err error) error

func HandleInvalidParamError

func HandleInvalidParamError(ctx context.Context, err error) error

func HandleMessagingError

func HandleMessagingError(ctx context.Context, st *spb.Status) error

func HandleNotFoundError

func HandleNotFoundError(ctx context.Context, err error) error

func HandleUpdateArgError

func HandleUpdateArgError(ctx context.Context, err error) error

func HandleUpdateError

func HandleUpdateError(ctx context.Context, err error) error

func HasPagination

func HasPagination(r *jsonapi.ListRequest) bool

func JSONAPIError

func JSONAPIError(w http.ResponseWriter, md metadata.MD, s *status.Status)

JSONAPIError generates JSONAPI formatted error message

func ListReqCtx

func ListReqCtx(params *JSONAPIParams, r *jsonapi.ListRequest) context.Context

ListReqCtx generate context data from list(collection) request

func NullToInt64

func NullToInt64(i dat.NullInt64) int64

func NullToString

func NullToString(s dat.NullString) string

func NullToTime

func NullToTime(nt dat.NullTime) *timestamp.Timestamp

func ProtoTimeStamp

func ProtoTimeStamp(ts *timestamp.Timestamp) time.Time
func SkipHTTPLinks(ctx context.Context) bool

SkipHTTPLinks looks up the context for the presence of gprc metadata for skipping the generation of HTTP links

func TimestampProto

func TimestampProto(t time.Time) *timestamp.Timestamp

Types

type APIFilter

type APIFilter struct {
	// Attribute of the resource on which the filter will be applied
	Attribute string
	// Type of filter for matching or exclusion
	Operator string
	// The value to match or exclude
	Expression string
	//
	Logic string
}

APIFilter is a container for filter parameters

type Error

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

Error can be used for all kind of application errors e.g. you would use it to define form errors or any other semantical application problems for more information see http://jsonapi.org/format/#errors

type ErrorLinks struct {
	About string `json:"about,omitempty"`
}

ErrorLinks is used to provide an About URL that leads to further details about the particular occurrence of the problem.

for more information see http://jsonapi.org/format/#error-objects

type ErrorSource

type ErrorSource struct {
	Pointer   string `json:"pointer,omitempty"`
	Parameter string `json:"parameter,omitempty"`
}

ErrorSource is used to provide references to the source of an error.

The Pointer is a JSON Pointer to the associated entity in the request document. The Paramter is a string indicating which query parameter caused the error.

for more information see http://jsonapi.org/format/#error-objects

type HTTPError

type HTTPError struct {
	Errors []Error `json:"errors,omitempty"`
	// contains filtered or unexported fields
}

HTTPError is used for errors

type JSONAPIParams

type JSONAPIParams struct {
	// contain include query paramters
	Includes []string
	// contain fields query paramters
	Fields []string
	// check for presence of fields parameters
	HasFields bool
	// check for presence of include parameters
	HasInclude bool
	// check for presence of filter parameters
	HasFilter bool
	// slice of filters
	Filters []*APIFilter
}

JSONAPIParams is a container for various JSON API query parameters

func ValidateAndParseGetParams

func ValidateAndParseGetParams(jsapi JSONAPIParamsInfo, r *jsonapi.GetRequest) (*JSONAPIParams, metadata.MD, error)

ValidateAndParseGetParams validate and parse the JSON API include and fields parameters that are used for singular resources

func ValidateAndParseListParams

func ValidateAndParseListParams(jsapi JSONAPIParamsInfo, r *jsonapi.ListRequest) (*JSONAPIParams, metadata.MD, error)

ValidateAndParseListParams validate and parse the JSON API include, fields, filter parameters

func ValidateAndParseSimpleListParams

func ValidateAndParseSimpleListParams(jsapi JSONAPIParamsInfo, r *jsonapi.SimpleListRequest) (*JSONAPIParams, metadata.MD, error)

ValidateAndParseSimpleListParams validate and parse the JSON API include, fields, filter parameters

type JSONAPIParamsInfo

type JSONAPIParamsInfo interface {
	// Relationships that could be included
	AllowedInclude() []string
	// Attribute fields that are allowed
	AllowedFields() []string
	// Filter fields that are allowed
	AllowedFilter() []string
	// FilterToColumns provides mapping between filter and storage columns
	FilterToColumns() map[string]string
	// RequiredAttrs are the mandatory attributes for creating a new resource
	RequiredAttrs() []string
}

JSONAPIParamsInfo interface should be implement by all grpc-gateway services that supports JSON API specifications.

type JSONAPIResource

type JSONAPIResource interface {
	//GetResourceName returns canonical resource name
	GetResourceName() string
	// GetBaseURL returns the base url with the scheme
	GetBaseURL() string
	// GetPrefix returns the path that could be appended to base url
	GetPathPrefix() string
}

JSONAPIResource interface provides information about HTTP resource. All grpc-gateway services that supports JSONAPI should implement this interface.

type Option

type Option func(*ServiceOptions)

func BaseURLOption

func BaseURLOption(base string) Option

func FieldsMappingOptions

func FieldsMappingOptions(fmap map[string]string) Option

func FilterMappingOptions

func FilterMappingOptions(fmap map[string]string) Option

func IncludeOptions

func IncludeOptions(inc []string) Option

func JSONAPIResourceOptions

func JSONAPIResourceOptions(prefix, resource, base string) Option

func ReqAttributesOption

func ReqAttributesOption(attr []string) Option

func TopicsOption

func TopicsOption(t map[string]string) Option

type Service

type Service struct {
	Dbh             *runner.DB
	PathPrefix      string
	Include         []string
	FieldsToColumns map[string]string
	Resource        string
	BaseURL         string
	FilToColumns    map[string]string
	ListMethod      bool
	ReqAttrs        []string
	Context         context.Context
	Topics          map[string]string
}

func (*Service) AllowedFields

func (s *Service) AllowedFields() []string

func (*Service) AllowedFilter

func (s *Service) AllowedFilter() []string

func (*Service) AllowedInclude

func (s *Service) AllowedInclude() []string

func (*Service) FilterToColumns

func (s *Service) FilterToColumns() map[string]string
func (s *Service) GenCollResourceRelSelfLink(id int64, relation string) string
func (s *Service) GenCollResourceSelfLink(ctx context.Context) string
func (s *Service) GenResourceSelfLink(ctx context.Context, id int64) string

func (*Service) GetAllFilteredCount

func (s *Service) GetAllFilteredCount(ctx context.Context, table string) (int64, error)

func (*Service) GetBaseURL

func (s *Service) GetBaseURL() string

func (*Service) GetCount

func (s *Service) GetCount(ctx context.Context, table string) (int64, error)

func (*Service) GetPagination

func (s *Service) GetPagination(ctx context.Context, record, pagenum, pagesize int64) (*jsonapi.PaginationLinks, int64)

GetPagination generates JSONAPI pagination links along with fields, include and filter query parameters

func (*Service) GetPathPrefix

func (s *Service) GetPathPrefix() string

func (*Service) GetRelatedPagination

func (s *Service) GetRelatedPagination(id, record, pagenum, pagesize int64, relation string) (*jsonapi.PaginationLinks, int64)

GetRelatedPagination generates JSONAPI pagination links for relation resources

func (*Service) GetResourceName

func (s *Service) GetResourceName() string

func (*Service) IsListMethod

func (s *Service) IsListMethod() bool

func (*Service) MapFieldsToColumns

func (s *Service) MapFieldsToColumns(fields []string) []string

func (*Service) RequiredAttrs

func (s *Service) RequiredAttrs() []string

func (*Service) SetBaseURL

func (s *Service) SetBaseURL() error

type ServiceOptions

type ServiceOptions struct {
	PathPrefix      string
	Resource        string
	BaseURL         string
	Include         []string
	FieldsToColumns map[string]string
	FilToColumns    map[string]string
	ReqAttrs        []string
	Topics          map[string]string
}

Jump to

Keyboard shortcuts

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