contract

package
v0.1.104 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2025 License: Apache-2.0 Imports: 30 Imported by: 118

Documentation

Index

Constants

View Source
const (
	MongoLookupFullDocument  MongoLookupTarget = "fullDocument"
	MongoLookupDocumentKey   MongoLookupTarget = "documentKey"
	MongoLookupOperationType MongoLookupTarget = "operationType"
	TypeArray                AtlasDataType     = "array"
	TypeBoolean              AtlasDataType     = "boolean"
	TypeDate                 AtlasDataType     = "date"
	TypeFacetDate            AtlasDataType     = "dateFacet"
	TypeNumber               AtlasDataType     = "number"
	TypeFacetNumber          AtlasDataType     = "numberFacet"
	TypeGeo                  AtlasDataType     = "geo"
	TypeDocument             AtlasDataType     = "document"
	TypeEmbeddedDoc          AtlasDataType     = "embeddedDocument"
	TypeObjectID             AtlasDataType     = "objectId"
	TypeString               AtlasDataType     = "string"
	TypeFacetString          AtlasDataType     = "stringFacet"
	TypeAutocomplete         AtlasDataType     = "autocomplete"
	TypeToken                AtlasDataType     = "token"
	VerbElemMatch            MongoVerb         = "$elemMatch"
	VerbMatch                MongoVerb         = "$match"
	VerbSkip                 MongoVerb         = "$skip"
	VerbLimit                MongoVerb         = "$limit"
	VerbSort                 MongoVerb         = "$sort"
	VerbCount                MongoVerb         = "$count"
	VerbSearch               MongoVerb         = "$search"
	OpAnd                    BSONOperator      = "$and"
	OpOr                     BSONOperator      = "$or"
	OpNor                    BSONOperator      = "$nor"
	OpGT                     BSONOperator      = "$gt"
	OpGTE                    BSONOperator      = "$gte"
	OpLT                     BSONOperator      = "$lt"
	OpLTE                    BSONOperator      = "$lte"
	OpNE                     BSONOperator      = "$ne"
	OpIn                     BSONOperator      = "$in"
	OpNin                    BSONOperator      = "$nin"
	Ascending                SortDirection     = 1
	Descending               SortDirection     = -1
	MatchAll                 MatchBehavior     = "$all"
	MatchIn                  MatchBehavior     = "$in"
	MatchEqual               MatchBehavior     = "$eq"
)
View Source
const (
	SearchQueryKey   = "q"
	SearchPageKey    = "page"
	SearchPerPageKey = "per_page"
)
View Source
const DefaultIndent = "  "
View Source
const (
	IDKey = "id"
)

Variables

View Source
var SearchRules = QueryParamRules{
	{
		Key:                   SearchQueryKey,
		DefaultValue:          "",
		MultipleValuesAllowed: false,
		Optional:              false,
	},
	{
		Key:                   SearchPageKey,
		DefaultValue:          "",
		MultipleValuesAllowed: false,
		Optional:              false,
	},
	{
		Key:                   SearchPerPageKey,
		DefaultValue:          "",
		MultipleValuesAllowed: false,
		Optional:              false,
	},
}

SearchRules defines validation rules for search queries.

Functions

This section is empty.

Types

type AtlasDataType added in v0.0.5

type AtlasDataType = string

AtlasDataType represents the data types recognized by MongoDB Atlas.

type AtlasIndexes added in v0.1.77

type AtlasIndexes map[string]string

AtlasIndexes is a map of field name to MongoDB Atlas data type.

func (AtlasIndexes) Fields added in v0.1.77

func (a AtlasIndexes) Fields() []string

Fields returns the keys of AtlasIndexes.

type AuthenticationResult added in v0.1.56

type AuthenticationResult struct {
	// Message is a descriptive message about the authentication result, written in Title Case.
	// example:Login Successful
	// readOnly:true
	Message string `json:"message,omitempty"`
	// User contains the authenticated user's details.
	// example:{"id":"123","name":"John Doe"}
	// readOnly:true
	User map[string]any `json:"user,omitempty"`
}

AuthenticationResult represents the response from an authentication operation. swagger:model

func NewAuthenticationResult added in v0.1.57

func NewAuthenticationResult(opts ...AuthenticationResultOption) *AuthenticationResult

type AuthenticationResultOption added in v0.1.56

type AuthenticationResultOption func(*AuthenticationResult)

func WithAuthMessage added in v0.1.56

func WithAuthMessage(x string) AuthenticationResultOption

func WithAuthUser added in v0.1.56

func WithAuthUser(x map[string]any) AuthenticationResultOption

type Authorizable added in v0.1.54

type Authorizable interface {
	Readers() []ID
	Writers() []ID
	Owners() []ID
}

type AuthorizationResult added in v0.1.56

type AuthorizationResult struct {
	// Code is the HTTP status code.
	// example:200
	// readOnly:true
	Code int `json:"code,omitempty"`
	// UnallowedEntities is the list of unauthorized entity IDs.
	// readOnly:true
	UnallowedEntities []ID `json:"unallowed_entities,omitempty"`
}

AuthorizationResult represents an authorization response. swagger:model

func NewAuthorizationResult added in v0.1.57

func NewAuthorizationResult(opts ...AuthorizationResultOption) *AuthorizationResult

type AuthorizationResultOption added in v0.1.56

type AuthorizationResultOption func(*AuthorizationResult)

func WithAuthCode added in v0.1.56

func WithAuthCode(x int) AuthorizationResultOption

func WithAuthUnallowedEntities added in v0.1.56

func WithAuthUnallowedEntities(x []ID) AuthorizationResultOption

type BSONOperator added in v0.0.5

type BSONOperator = string

BSONOperator represents BSON query operators in MongoDB.

type Base64Decoder added in v0.0.5

type Base64Decoder interface {
	DecodeString(enc *base64.Encoding, src string) ([]byte, error)
}

type BasisInt added in v0.1.10

type BasisInt = int

type BasisInt32 added in v0.1.10

type BasisInt32 = int32

type BasisInt64 added in v0.1.10

type BasisInt64 = int64

type BasisOperator added in v0.1.10

type BasisOperator interface {
	BasisIntToMajor(b BasisInt, c ConversionFactor) MajorUnit
	BasisInt32ToMajor(b BasisInt32, c ConversionFactor) MajorUnit
	BasisInt64ToMajor(b BasisInt64, c ConversionFactor) MajorUnit
	MajorToBasis(m MajorUnit, c ConversionFactor) (BasisInt64, error)
}

type CacheHit added in v0.0.5

type CacheHit struct {
	V string `json:"v"`
}

CacheHit represents a cache entry that holds a JSON string.

type CacheHitter added in v0.0.5

type CacheHitter interface {
	DecodeHit(c CacheHit, dst any) error
	HitFromValue(v any) (*CacheHit, error)
}

type CacheID added in v0.0.5

type CacheID string

func (CacheID) String added in v0.0.5

func (c CacheID) String() string

type CacheIdentifier added in v0.0.5

type CacheIdentifier interface {
	CacheID(id string) (CacheID, error)
}

type CacheKey added in v0.0.5

type CacheKey struct {
	ID           fmt.Stringer
	Microservice string
	Collection   string
	Multi        *CacheMulti
}

CacheKey represents a cache key. It is used to identify a cache entry & it can be used to generate a matching pattern using wildcards.

func (CacheKey) String added in v0.0.5

func (c CacheKey) String() string

String implements the Stringer interface for Key.

type CacheMulti added in v0.0.5

type CacheMulti struct {
	RawQuery string
}

type CacheOperator added in v0.0.5

type CacheOperator interface {
	CacheIdentifier
	CacheHitter
	Cacher
}

type Cacher added in v0.0.5

type Cacher interface {
	CloserWithCtx
	Get(ctx context.Context, c fmt.Stringer) (*CacheHit, error)
	Set(ctx context.Context, c fmt.Stringer, v CacheHit) error
	BatchGet(ctx context.Context, c []fmt.Stringer) ([]CacheHit, error)
	BatchSet(ctx context.Context, e map[fmt.Stringer]CacheHit) error
	Flush(ctx context.Context, c fmt.Stringer) error
	BatchFlush(ctx context.Context, c []fmt.Stringer) error
	FlushAll(ctx context.Context) error
	Exists(ctx context.Context, c fmt.Stringer) (bool, error)
}

type CertGenerator added in v0.0.5

type CertGenerator interface {
	X509KeyPair(certPEMBlock []byte, keyPEMBlock []byte) (tls.Certificate, error)
	AppendCertsFromPEM(pool *x509.CertPool, pemCerts []byte) (ok bool)
}

type ChangeEvent added in v0.0.5

type ChangeEvent struct {
	OperationType string `json:"operation_type"`
	FullDocument  any    `json:"full_document"`
}

type Closer added in v0.1.13

type Closer interface {
	Close() error
}

type CloserWithCtx added in v0.1.13

type CloserWithCtx interface {
	Close(ctx context.Context) error
}

type ComponentExtractor added in v0.1.10

type ComponentExtractor interface {
	GetComponent(skip int, withFuncPath, withFile, withFilePath, withLine bool) string
}

type ConversionFactor added in v0.1.10

type ConversionFactor = int64

type CreateCollectionsOptions added in v0.1.37

type CreateCollectionsOptions struct {
	Collections []string
}

type CreateIndexesOptions added in v0.1.37

type CreateIndexesOptions struct {
	Collection string
	Indexes    []IndexEntry
}

type CreateSearchIndexesOptions added in v0.1.37

type CreateSearchIndexesOptions struct {
	Collection string
	Indexes    []SearchIndexEntry
}

type DBOperator added in v0.0.5

type DBOperator interface {
	InsertOne(ctx context.Context, opts InsertOneOptions) error
	FindOne(ctx context.Context, opts FindOneOptions) error
	FindMany(ctx context.Context, opts FindManyOptions) ([]any, error)
	ReplaceOne(ctx context.Context, opts ReplaceOneOptions) error
	DeleteOne(ctx context.Context, opts DeleteOneOptions) error
	DeleteMany(ctx context.Context, opts DeleteManyOptions) error
	CloserWithCtx
}

type DateFilterOptions added in v0.0.5

type DateFilterOptions struct {
	YearField  string
	MonthField string
	DayField   string
	RefYear    uint
	RefMonth   uint
	RefDay     uint
	IncludeDay bool
}

type DecodeCursorOptions added in v0.0.5

type DecodeCursorOptions struct {
	Cursor   MongoCursor
	Receiver any
}

type DeleteManyOptions added in v0.0.5

type DeleteManyOptions struct {
	Collection string
	Filter     bson.M
}

type DeleteOneOptions added in v0.0.5

type DeleteOneOptions struct {
	Collection string
	IDKey      string
	ID         Identifier
}

type ElemMatchFilterOptions added in v0.0.5

type ElemMatchFilterOptions struct {
	ArrayField string
	Element    any
	PrependStr string
	AppendStr  string
}

type ElemsInArrayFilterOptions added in v0.0.5

type ElemsInArrayFilterOptions struct {
	ArrayField string
	Elements   []any
	PrependStr string
	AppendStr  string
}

type Entry added in v0.1.10

type Entry struct {
	Handler HandlerFunc
	Weight  uint
}

Entry maps an HTTP handler to a request weight.

type Env added in v0.1.80

type Env string
const (
	Local   Env = "local"
	Dev     Env = "dev"
	Staging Env = "staging"
	Prod    Env = "prod"
)

func (Env) LogLvl added in v0.1.104

func (e Env) LogLvl() slog.Level

func (Env) RewriteHost added in v0.1.80

func (e Env) RewriteHost(u *url.URL)

func (Env) Verify added in v0.1.104

func (e Env) Verify() error

type FSysFileReader

type FSysFileReader interface {
	FSysReadFile(fsys fs.ReadFileFS, path string) ([]byte, error)
}

type FactoryOperator added in v0.1.10

type FactoryOperator interface {
	New(name string) (any, error)
}

type FieldInArrayFilterOptions added in v0.0.5

type FieldInArrayFilterOptions struct {
	Field    string
	Elements []any
}

type FilterOptions added in v0.0.5

type FilterOptions struct {
	ConvertValues  bool
	QueryParams    map[string][]string
	MatchBehavior  MatchBehavior
	PrependStr     string
	AppendStr      string
	ExcludedFields []string
}

type FindManyInternalOptions added in v0.1.63

type FindManyInternalOptions struct {
	Filter        bson.M
	SortByKey     string
	SortDirection SortDirection
	Skip          int64
	Limit         int64
}

type FindManyOptions added in v0.0.5

type FindManyOptions struct {
	FindManyInternalOptions
	Collection string
	Receiver   any
}

type FindOneOptions added in v0.0.5

type FindOneOptions struct {
	Collection string
	Receiver   any
	IDKey      string
	ID         Identifier
}

type FirebaseOperator added in v0.1.10

type FirebaseOperator interface {
	GetFirebaseIDToken(ctx context.Context, email, password, firebaseAPIKey string) (string, error)
	InitFirebase(ctx context.Context, fsys fs.ReadFileFS, accountCredentialsPath string) (*firebase.App, error)
	GenerateMockFirebaseUID(length int) string
}

type Geocoder

type Geocoder interface {
	TimezoneFromCoordinates(ctx context.Context, latitude, longitude float64) (string, error)
	CityFromCoordinates(ctx context.Context, latitude, longitude float64) (string, error)
	TimezoneDataFromCoordinates(ctx context.Context, latitude, longitude float64) (*maps.TimezoneResult, error)
	GeocodeCoordinates(ctx context.Context, latitude, longitude float64) ([]maps.GeocodingResult, error)
	SwapTimezone(t time.Time, tz string, toUTC, toMidnight bool) (time.Time, error)
	IsUTC(t time.Time) bool
}

type GoogleMaps added in v0.0.5

type GoogleMaps interface {
	Timezone(ctx context.Context, r *maps.TimezoneRequest) (*maps.TimezoneResult, error)
	Geocode(ctx context.Context, r *maps.GeocodingRequest) ([]maps.GeocodingResult, error)
}

type GzipReader

type GzipReader interface {
	Read(r io.Reader) (io.Reader, error)
}

type GzipUtil

type GzipUtil interface {
	WriteGzip(w *gzip.Writer, r io.Reader) error
	CloseGzipWriter(w *gzip.Writer) error
	ReadGzip(r io.Reader) ([]byte, error)
	NewGzipReader(r io.Reader) (*gzip.Reader, error)
	CopyToBuffer(r *gzip.Reader, buf *bytes.Buffer) error
	CloseGzipReader(r *gzip.Reader) error
}

type GzipWriter

type GzipWriter interface {
	Write(r io.Reader) (io.Reader, int64, error)
}

type HTTPClient added in v0.0.5

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type HTTPDoer

type HTTPDoer interface {
	Do(ctx context.Context, r *http.Request) (*http.Response, error)
}

type HTTPHTML added in v0.1.5

type HTTPHTML interface {
	ServeHTML(w http.ResponseWriter, body io.Reader, status int) error
}

type HTTPRequester

type HTTPRequester interface {
	NewRequest(ctx context.Context, method, url string, opts RequestOptions) (*http.Request, error)
}

type HTTPResponder added in v0.1.5

type HTTPResponder interface {
	RespondJSON(w http.ResponseWriter, v any, status int, escapeHTML bool)
}

type HTTPResponseWriter added in v0.1.14

type HTTPResponseWriter interface {
	Header() http.Header
	Write([]byte) (int, error)
	WriteHeader(statusCode int)
}

type HTTPServer added in v0.1.10

type HTTPServer interface {
	ListenAndServe() error
	ListenAndServeTLS(certFile string, keyFile string) error
	Shutdown(ctx context.Context) error
}

type HTTPUtil added in v0.1.5

type HTTPUtil interface {
	QueryString(pairs ...string) string
	ValidateQueryParams(q map[string][]string, rules ...QueryParamRule) error
	CopyHeaders(dst, src *http.Request, headers ...string)
	GetHeaders(r *http.Request) http.Header
	DecodeBody(r *http.Request, v any) error
}

type HTTPWriter

type HTTPWriter interface {
	Write(w http.ResponseWriter, b []byte) (int, error)
}

type HandlerFunc added in v0.1.11

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

HandlerFunc defines a handler function.

func (HandlerFunc) Wrap added in v0.1.11

type ID added in v0.0.8

type ID struct {
	// V is a unique identifier.
	// example: 123e4567-e89b-12d3-a456-426655440000
	// required:true
	V *string `json:"id"`
}

ID is a custom type for database-agnostic unique IDs. swagger:model

func NewID added in v0.0.8

func NewID() *ID

NewDBID generates a new ID.

func NewIDFromQVals added in v0.1.61

func NewIDFromQVals(q config.QVals) *ID

func NewIDFromString added in v0.0.8

func NewIDFromString(v string) *ID

NewIDFromString converts string to ID.

func (*ID) GetV added in v0.0.8

func (id *ID) GetV() string

func (*ID) IsEmpty added in v0.0.8

func (id *ID) IsEmpty() bool

IsEmpty checks if the ID is empty.

func (ID) MarshalBSON added in v0.0.8

func (id ID) MarshalBSON() ([]byte, error)

MarshalBSON implements the bson.Marshaler interface for Mongo compatibility.

func (ID) MarshalJSON added in v0.1.40

func (id ID) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*ID) SetV added in v0.0.8

func (id *ID) SetV(x string)

func (ID) String added in v0.0.8

func (id ID) String() string

String implements the Stringer interface.

func (*ID) UnmarshalBSON added in v0.0.8

func (id *ID) UnmarshalBSON(data []byte) error

UnmarshalBSON implements the bson.Unmarshaler interface for Mongo compatibility.

func (*ID) UnmarshalJSON added in v0.1.40

func (id *ID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type Identifiable added in v0.0.5

type Identifiable interface {
	GetID() ID
}

type Identifier added in v0.0.5

type Identifier interface {
	GetV() string
	SetV(string)
	IsEmpty() bool
	fmt.Stringer
}

type IndexEntry added in v0.0.5

type IndexEntry struct {
	Name               string
	Field              string
	Type               int32
	ExpireAfterSeconds *int32
}

type InsertOneOptions added in v0.0.5

type InsertOneOptions struct {
	Collection string
	Document   Identifiable
}

type JSONOption

type JSONOption func(*JSONOptions)

func WithJSONEscapeHTML

func WithJSONEscapeHTML(escape bool) JSONOption

func WithJSONIndent

func WithJSONIndent(indent string) JSONOption

func WithJSONUseNumber

func WithJSONUseNumber(use bool) JSONOption

type JSONOptions

type JSONOptions struct {
	Indent     string // Enables indentation if non-empty.
	EscapeHTML bool   // Determines if HTML characters should be escaped.
	UseNumber  bool   // If true, decodes numbers as `json.Number` instead of `float64`.
}

JSONOptions defines settings for encoding/decoding.

func ApplyJSONOptions

func ApplyJSONOptions(opts *JSONOptions, modifiers ...JSONOption) JSONOptions

type Level

type Level = slog.Level
const (
	Debug Level = slog.LevelDebug
	Info  Level = slog.LevelInfo
	Warn  Level = slog.LevelWarn
	Error Level = slog.LevelError
)

type LibraryOperator added in v0.1.45

type LibraryOperator interface {
	Svc() string
	Env() string
}

type LimiterInfo added in v0.1.11

type LimiterInfo interface {
	GetMaxScore() uint
	GetHeaderKey() string
	GetRateLimitingMode() string
}

type LimiterOperator added in v0.1.10

type LimiterOperator interface {
	Engage(next HandlerFunc) HandlerFunc
	LimiterInfo
}

type LogOperator added in v0.1.10

type LogOperator interface {
	Log(ctx context.Context, l Level, v any, prefix string, msg ...string)
	Wrap(ctx context.Context, fn func() (any, error)) error
}

type MajorUnit added in v0.1.10

type MajorUnit = float64

type Marshaler

type Marshaler interface {
	Marshal(v any, opts JSONOptions) ([]byte, error)
}

type MatchBehavior added in v0.0.5

type MatchBehavior = string

MatchBehavior defines different matching behaviors in MongoDB queries, such as in, all, and eq.

type MiddlewareFunc added in v0.1.10

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc defines a composable middleware around a HandlerFunc.

type MiddlewareOperator added in v0.1.10

type MiddlewareOperator interface {
	Chain(handlers ...MiddlewareFunc) MiddlewareFunc
	Gzip(next HandlerFunc) HandlerFunc
	EnforceHTTPS(next HandlerFunc) HandlerFunc
	CheckHeaders(next HandlerFunc) HandlerFunc
	CleanURLPath(next HandlerFunc) HandlerFunc
	IdempotentPOST(next HandlerFunc) HandlerFunc
	RequireReader(next HandlerFunc) HandlerFunc
	RequireWriter(next HandlerFunc) HandlerFunc
	RequireOwner(next HandlerFunc) HandlerFunc
	AuthenticateFirebaseIDToken(next HandlerFunc) HandlerFunc
	AuthenticateOIDCToken(next HandlerFunc) HandlerFunc
}

type MongoChangeStream added in v0.0.5

type MongoChangeStream interface {
	Close(ctx context.Context) error
	Next(ctx context.Context) bool
	Err() error
}

type MongoClient added in v0.0.5

type MongoClient interface {
	Database(name string, opts ...options.Lister[options.DatabaseOptions]) *mongo.Database
	StartSession(opts ...options.Lister[options.SessionOptions]) (*mongo.Session, error)
	Disconnect(ctx context.Context) error
}

type MongoCollection added in v0.0.5

type MongoCollection interface {
	InsertOne(ctx context.Context, document any, opts ...options.Lister[options.InsertOneOptions]) (*mongo.InsertOneResult, error)
	FindOne(ctx context.Context, filter any, opts ...options.Lister[options.FindOneOptions]) *mongo.SingleResult
	Find(ctx context.Context, filter any, opts ...options.Lister[options.FindOptions]) (*mongo.Cursor, error)
	ReplaceOne(ctx context.Context, filter any, document any, opts ...options.Lister[options.ReplaceOptions]) (*mongo.UpdateResult, error)
	DeleteOne(ctx context.Context, filter any, opts ...options.Lister[options.DeleteOneOptions]) (*mongo.DeleteResult, error)
	DeleteMany(ctx context.Context, filter any, opts ...options.Lister[options.DeleteManyOptions]) (*mongo.DeleteResult, error)
	Aggregate(ctx context.Context, pipeline any, opts ...options.Lister[options.AggregateOptions]) (*mongo.Cursor, error)
	Watch(ctx context.Context, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*mongo.ChangeStream, error)
}

type MongoCursor added in v0.0.5

type MongoCursor interface {
	Next(ctx context.Context) bool
	Decode(receiver any) error
	Err() error
}

type MongoDatabase added in v0.0.5

type MongoDatabase interface {
	Watch(ctx context.Context, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*mongo.ChangeStream, error)
}

type MongoFilter added in v0.0.5

type MongoFilter interface {
	Filter(opts FilterOptions) (bson.M, error)
	FilterByFieldInArray(opts FieldInArrayFilterOptions) bson.M
	FilterByElemMatch(opts ElemMatchFilterOptions) bson.M
	FilterByElemsInArray(opts ElemsInArrayFilterOptions) bson.M
	FilterByAllElemsInArray(opts ElemsInArrayFilterOptions) bson.M
	FilterByFutureDate(opts DateFilterOptions) bson.D
	FilterByPastDate(opts DateFilterOptions) bson.D
	FilterByExactDate(opts DateFilterOptions) bson.D
	CombineM(op BSONOperator, m ...bson.M) bson.M
}

type MongoLookupTarget added in v0.0.5

type MongoLookupTarget = string

MongoLookupTarget specifies the target field for the lookup stage in a MongoDB aggregation pipeline.

type MongoOperator added in v0.0.5

type MongoOperator interface {
	MongoUtil
	MongoFilter
	MongoSpecialized
	CloserWithCtx
}

type MongoOutCSChan added in v0.0.5

type MongoOutCSChan = chan *ChangeEvent

MongoOutCSChan is a channel type used for sending decoded MongoDB change events.

type MongoPipeliner added in v0.0.5

type MongoPipeliner interface {
	Pipeline() mongo.Pipeline
}

type MongoSpecialized added in v0.0.5

type MongoSpecialized interface {
	Search(ctx context.Context, opts SearchOptions) (*SearchResult, error)
	WatchCollection(ctx context.Context, opts WatchCollectionOptions) error
	WatchDB(ctx context.Context, opts WatchDBOptions) error
	ProcessChangeStream(ctx context.Context, opts ProcessChangeStreamOptions) error
	RunPipeline(ctx context.Context, opts RunPipelineOptions) ([]any, error)
}

type MongoUtil added in v0.0.5

type MongoUtil interface {
	WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error
	Collection(db, collection string) MongoCollection
	Database(db string) MongoDatabase
}

type MongoVerb added in v0.0.5

type MongoVerb = string

MongoVerb defines a MongoDB operation keyword, such as match.

type OperationResult added in v0.1.56

type OperationResult struct {
	// Message is the optional operation message.
	// example:Record Retrieved Successfully
	// readOnly:true
	Message string `json:"message,omitempty"`
	// ID is the optional resource identifier.
	// example:123e4567-e89b-12d3-a456-426655440000
	// readOnly:true
	ID *ID `json:"id,omitempty"`
	// Value is an optional result object.
	// readOnly:true
	Value any `json:"value,omitempty"`
}

Operation is a general-purpose response struct. swagger:model

func NewOperationResult added in v0.1.57

func NewOperationResult(opts ...OperationResultOption) *OperationResult

type OperationResultOption added in v0.1.56

type OperationResultOption func(*OperationResult)

func WithID added in v0.1.56

func WithID(x *ID) OperationResultOption

func WithMessage added in v0.1.56

func WithMessage(x string) OperationResultOption

func WithValue added in v0.1.56

func WithValue(x any) OperationResultOption

type PaginationOptions added in v0.0.5

type PaginationOptions struct {
	PageNumber int32
	PageSize   int32
}

func (*PaginationOptions) Verify added in v0.0.5

func (p *PaginationOptions) Verify() error

type PeriodOperator added in v0.1.10

type PeriodOperator interface {
	FirstPeriodStartDate(year int) time.Time
	LastDayOfLastPeriod(year int) time.Time
	FirstDayOfMonth(date time.Time) time.Time
	PeriodNumber(date time.Time) int
	TimeOfWeekday(date time.Time, weekday time.Weekday) time.Time
}

type PoolOperator added in v0.1.10

type PoolOperator interface {
	Acquire()
	Release()
	ActiveWorkers() int
	WaitAll()
	Shutdown()
}

type ProcessChangeStreamOptions added in v0.0.5

type ProcessChangeStreamOptions struct {
	ChangeStream MongoChangeStream
	LookupKey    string
	Receiver     any
	Output       MongoOutCSChan
}

type PubSubMessage added in v0.0.5

type PubSubMessage interface {
	GetData() []byte
	GetAttributes() map[string]string
	GetMessageID() string
	GetPublishTime() time.Time
}

type PubSubOperator added in v0.1.10

type PubSubOperator interface {
	MockPubSubPayload(msg PubSubMessage, subscription string) (io.Reader, error)
	DecodePayload(r *http.Request) (PubSubMessage, error)
}

type QueryParamRule added in v0.1.5

type QueryParamRule struct {
	Key                   string   // Name of the query parameter.
	DefaultValue          string   // Default value if not provided in the request.
	AcceptedValues        []string // Accepted values; nil allows any value.
	MultipleValuesAllowed bool     // Whether multiple values are permitted.
	Optional              bool     // Whether the parameter is optional.
}

QueryParamRule defines validation rules for a query parameter. It specifies constraints such as key, default value, allowed values, and multiplicity.

type QueryParamRules added in v0.1.72

type QueryParamRules []QueryParamRule

func (*QueryParamRules) AppendMany added in v0.1.73

func (q *QueryParamRules) AppendMany(r QueryParamRules)

AppendMany appends multiple QueryParamRules to the QueryParamRules.

func (*QueryParamRules) AppendOne added in v0.1.73

func (q *QueryParamRules) AppendOne(r QueryParamRule)

Append appends a QueryParamRule to the QueryParamRules.

type Queryable added in v0.1.68

type Queryable interface {
	Rules() QueryParamRules
}

type RawCacheKey added in v0.1.3

type RawCacheKey string

RawCacheKey wraps a string key to implement fmt.Stringer.

func (RawCacheKey) String added in v0.1.3

func (r RawCacheKey) String() string

String implements the Stringer interface for RawCacheKey.

type Reader

type Reader interface {
	Read(io.Reader) ([]byte, error)
}

type RedisClient added in v0.0.5

type RedisClient interface {
	Closer
	Get(ctx context.Context, key string) *redis.StringCmd
	Set(ctx context.Context, key string, value any, expiration time.Duration) *redis.StatusCmd
	FlushAll(ctx context.Context) *redis.StatusCmd
	Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanCmd
	TxPipeline() redis.Pipeliner
	Exists(ctx context.Context, keys ...string) *redis.IntCmd
	Pipeline() redis.Pipeliner
}

type RedisOperator added in v0.1.10

type RedisOperator interface {
	Cacher
}

type ReflectOperator added in v0.1.10

type ReflectOperator interface {
	FillNilPointers(to, from any) error
}

type RegisteredRoute added in v0.1.10

type RegisteredRoute struct {
	MethodMap map[string]Entry
}

RegisteredRoute holds a map of HTTP methods to route entries.

type Registry added in v0.1.10

type Registry map[*regexp.Regexp]*RegisteredRoute

Registry maps compiled regex patterns to registered routes.

func (*Registry) LenHandlers added in v0.1.10

func (r *Registry) LenHandlers() int

LenHandlers returns the total number of handlers across all routes.

func (*Registry) LenRoutes added in v0.1.10

func (r *Registry) LenRoutes() int

LenRoutes returns the number of registered routes.

type RegistryMutex added in v0.1.10

type RegistryMutex struct {
	sync.RWMutex
}

RegistryMutex provides thread-safe access to the route registry.

type ReplaceOneOptions added in v0.0.5

type ReplaceOneOptions struct {
	Collection string
	Document   Identifiable
	IDKey      string
	ID         Identifier
}

type RequestOption

type RequestOption func(*RequestOptions)

func WithRequestBody

func WithRequestBody(body io.Reader) RequestOption

func WithRequestHeader

func WithRequestHeader(header http.Header) RequestOption

type RequestOptions

type RequestOptions struct {
	Header http.Header
	Body   io.Reader
}

func ApplyRequestOptions

func ApplyRequestOptions(opts *RequestOptions, modifiers ...RequestOption) RequestOptions

type RequestWeight added in v0.1.10

type RequestWeight = uint

RequestWeight defines the relative cost of a request for rate limiting.

const (
	// Unlimited disables rate limiting for the request.
	Unlimited RequestWeight = 0
)

type Role added in v0.1.50

type Role int
const (
	NA Role = iota
	Rdr
	Wrtr
	Ownr
)

func (Role) Validate added in v0.1.50

func (r Role) Validate() error

type Route added in v0.1.10

type Route struct {
	Ressource   string
	Pairs       []string
	HandlerFunc HandlerFunc
	Weight      uint
	Methods     []string
}

Route holds route metadata to be compiled and registered.

func (Route) CompileRegex added in v0.1.10

func (r Route) CompileRegex(pathKey string) (*regexp.Regexp, error)

compileRegex builds a compiled regex for matching the route.

func (*Route) Validate added in v0.1.10

func (r *Route) Validate() error

validate checks whether the route definition is valid.

type RouterOperator added in v0.1.10

type RouterOperator interface {
	RouterParser
	Run() error
	Mount(r []*Route) error
	Stop(ctx context.Context) error
	Vars(ctx context.Context) (*config.Vars, error)
	PKey() string
	AttachServer(s ServerOperator)
}

type RouterParser added in v0.1.27

type RouterParser interface {
	ParsePath(r *http.Request, re *regexp.Regexp) map[string]string
	ParseQuery(r *http.Request) map[string][]string
}

type RunPipelineOptions added in v0.1.79

type RunPipelineOptions struct {
	Collection string
	Receiver   any
	Pipeline   MongoPipeliner
}

type Scopable added in v0.1.60

type Scopable interface {
	Scope() Scope
}

type Scope added in v0.1.66

type Scope struct {
	K  string
	ID ID
}

type SearchIndexEntry added in v0.0.5

type SearchIndexEntry struct {
	Collection  string
	Fields      AtlasIndexes
	VectorField *VectorSearchField
}

type SearchInternalOptions added in v0.1.67

type SearchInternalOptions struct {
	Filter    bson.M
	SortByKey string
	SortDir   SortDirection
}

type SearchOptions added in v0.0.5

type SearchOptions struct {
	SearchInternalOptions
	Collection string
	Receiver   any
	T          *TextOptions
	P          *PaginationOptions
}

type SearchResult added in v0.1.56

type SearchResult struct {
	// Results is the list of search results.
	// example:[{"id":"1","name":"Item1"},{"id":"2","name":"Item2"}]
	// readOnly:true
	Results []any `json:"results,omitempty"`
	// TotalCount is the total number of matching results.
	// example:100
	// readOnly:true
	TotalCount int32 `json:"total_count,omitempty"`
	// LastPage is the last page number based on total results.
	// example:10
	// readOnly:true
	LastPage int32 `json:"last_page,omitempty"`
}

SearchResult represents the response from a search operation. swagger:model

func NewSearchResult added in v0.1.57

func NewSearchResult(opts ...SearchResultOption) *SearchResult

type SearchResultOption added in v0.1.56

type SearchResultOption func(*SearchResult)

func WithSearchLastPage added in v0.1.56

func WithSearchLastPage(x int32) SearchResultOption

func WithSearchResults added in v0.1.56

func WithSearchResults(x []any) SearchResultOption

func WithSearchTotalCount added in v0.1.56

func WithSearchTotalCount(x int32) SearchResultOption

type Searchable added in v0.1.75

type Searchable interface {
	SearchIn() []string
}

type SecretInfo added in v0.1.13

type SecretInfo struct {
	ProjectID string
	SecretID  string
	VersionID string
}

SecretInfo holds the identifiers needed to access a secret.

func (SecretInfo) BuildSecretName added in v0.1.13

func (s SecretInfo) BuildSecretName() string

BuildSecretName constructs the full secret name path for Secret Manager.

type SecretManagerClient added in v0.1.13

type SecretManagerClient interface {
	AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error)
	Close() error
}

type SecretOperator added in v0.1.13

type SecretOperator interface {
	GetSecret(ctx context.Context, s SecretInfo) ([]byte, error)
	Close() error
}

type SemaphoreInfo added in v0.1.11

type SemaphoreInfo interface {
	GetConcurrency() int
}

type SemaphoreOperator added in v0.1.10

type SemaphoreOperator interface {
	Acquire()
	Release()
	WaitAll()
	SemaphoreInfo
}

type ServerInfo added in v0.1.11

type ServerInfo interface {
	GetUseHTTP2() bool
	GetUseH2C() bool
	GetBoundOn() string
	GetIdleTimeout() time.Duration
	GetReadTimeout() time.Duration
	GetWriteTimeout() time.Duration
}

type ServerOperator added in v0.1.11

type ServerOperator interface {
	http.Handler
	ServerRunner
	ServerInfo
}

type ServerRunner added in v0.1.11

type ServerRunner interface {
	Run() error
	Shutdown(ctx context.Context) error
}

type SortDirection added in v0.0.5

type SortDirection int

SortDirection represents the sorting order for MongoDB queries.

type Sortable added in v0.1.62

type Sortable interface {
	SortBy() string
}

type TextOptions added in v0.0.5

type TextOptions struct {
	Query  string
	Fields []string
}

type Tool

type Tool[C any] struct {
	Client C
	Logger LogOperator
}

func NewTool

func NewTool[C any](client C, opts ToolOptions[C]) *Tool[C]

type ToolOption

type ToolOption[C any] func(*ToolOptions[C])

func WithLogger

func WithLogger[C any](x LogOperator) ToolOption[C]

type ToolOptions

type ToolOptions[C any] struct {
	Logger LogOperator
}

func ApplyToolOptions added in v0.1.12

func ApplyToolOptions[C any](opts *ToolOptions[C], modifiers ...ToolOption[C]) ToolOptions[C]

type Unmarshaler

type Unmarshaler interface {
	Unmarshal(data io.Reader, v any, opts JSONOptions) error
}

type VectorSearchField added in v0.0.5

type VectorSearchField struct {
	NumDimensions int
	Field         string
	Similarity    string
	Quantization  string
	Additionals   []string
}

type WatchCollectionOptions added in v0.0.5

type WatchCollectionOptions struct {
	Collection string
	Receiver   any
	Pipeline   MongoPipeliner
	Options    *options.ChangeStreamOptionsBuilder
	LookupKey  string
	Output     MongoOutCSChan
}

type WatchDBOptions added in v0.0.5

type WatchDBOptions struct {
	Receiver  any
	Pipeline  MongoPipeliner
	Options   *options.ChangeStreamOptionsBuilder
	LookupKey string
	Output    MongoOutCSChan
}

Jump to

Keyboard shortcuts

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