utility

package
v1.8.23 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: Apache-2.0 Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const (
	NamingSchemaVersionLegacy = 0
	NamingSchemaVersionV2     = 1
)

Naming schema version stored on ProjectSchema.NamingSchemaVersion.

View Source
const (
	GOROUTINE_WARNING_THRESHOLD  = 500
	GOROUTINE_CRITICAL_THRESHOLD = 1000
	GOROUTINE_CHECK_INTERVAL     = 30 * time.Second
)
View Source
const EchoTokenClaimsKey = "token_claims"

EchoTokenClaimsKey is the Echo context key for the parsed TokenClaims pointer.

View Source
const ErrQuotaExceeded = "plan quota exceeded"

ErrQuotaExceeded is returned when a create would exceed a plan quota.

View Source
const QuotaKeyAppUsers = "max_app_users"

QuotaKeyAppUsers is the quotas map key for max app users in a tenant.

View Source
const QuotaKeyRecordsPrefix = "max_records."

QuotaKeyRecordsPrefix prefixes per-model record limits: max_records.<model>.

View Source
const QuotaKeyStorageMB = "storage_mb"

QuotaKeyStorageMB is the quotas map key for storage limit in megabytes.

Variables

View Source
var (
	// ErrRunOnModelName is returned when the input has no word-boundary signal
	// and looks like concatenated words (e.g. foodorder). Users must use
	// food_order, food-order, foodOrder, or "food order".
	ErrRunOnModelName = errors.New("model name needs a word boundary between words: use food_order, food-order, foodOrder, or \"food order\"")

	// ErrInvalidModelName is returned when the normalized id does not match canonical rules.
	ErrInvalidModelName = errors.New("invalid model name: use lowercase snake_case with letters, numbers, and underscores only")
)
View Source
var DefaultMarkdownProcessor = NewMarkdownProcessor()

Global instance for easy access

View Source
var MapActionName = map[string]string{
	"UpdateProfileResolverFn":             "update user profile",
	"UpsertPluginResolverFn":              "plugin modification",
	"GenerateApiTokenResolverFn":          "generated api token",
	"DeleteApiTokenResolverFn":            "deleted api token",
	"CreateWebHookResolverFn":             "created a webhook",
	"DeleteWebHookResolverFn":             "deleted a webhook",
	"UpdateProjectResolverFn":             "updated a project information",
	"AddModelToProjectResolverFn":         "added a model to a project",
	"UpdateModelResolverFn":               "updated a model",
	"UpsertRoleToProjectResolverFn":       "added or modified a role to a project",
	"DuplicateRoleInProjectResolverFn":    "duplicated a role in a project",
	"DeleteRoleResolverFn":                "deleted a role",
	"UpsertFieldToModelResolverFn":        "added or modified a field to a model",
	"DeleteFieldTypeResolverFn":           "deleted a field",
	"ModelFieldOperationResolverFn":       "modified a field of a model",
	"CreateConnectionTypeResolverFn":      "created a connection between models",
	"DeleteConnectionFromModelResolverFn": "removed a connection between models",
	"UpsertModelDataFnFn":                 "added or modified data of a model",
	"DeleteModelDataFnFn":                 "deleted data of a model",
}
View Source
var SupportedLocals = []string{}/* 609 elements not displayed */

Functions

func AddDaysWithCurrentDhakaTime

func AddDaysWithCurrentDhakaTime(days int) string

func AddDaysWithCurrentTime

func AddDaysWithCurrentTime(days int) string

func ApplicationCacheFromContext added in v1.6.0

func ApplicationCacheFromContext(ctx context.Context) (*models.ApplicationCache, bool)

ApplicationCacheFromContext returns the cache set by WithApplicationCache.

func ArrayContains

func ArrayContains(arr []string, str string) bool

func ArrayContainsInterface

func ArrayContainsInterface(arr []interface{}, val interface{}) bool

func AuthorizeModelCreate added in v1.8.12

func AuthorizeModelCreate(role *models.Role, modelName string) error

AuthorizeModelCreate checks create access for a model. none → deny; auth → require IsProjectUser; all → ok. own/custom_logic/unknown → deny.

func AuthorizeModelDelete added in v1.8.12

func AuthorizeModelDelete(role *models.Role, modelName string, docCreatedByUserID string, docIsUserModel bool, paramUserID string) error

AuthorizeModelDelete checks delete access with the same own semantics as update.

func AuthorizeModelRead added in v1.8.12

func AuthorizeModelRead(role *models.Role, modelName string) error

AuthorizeModelRead checks read access for a model. none → deny; auth → require IsProjectUser; own → require IsProjectUser (row filter is driver's job); all → ok. Unknown scopes fail closed. RoleBypassesDataACL → ok.

func AuthorizeModelUpdate added in v1.8.12

func AuthorizeModelUpdate(role *models.Role, modelName string, docCreatedByUserID string, docIsUserModel bool, paramUserID string) error

AuthorizeModelUpdate checks update access. For own: user model → paramUserID must equal doc ID (pass doc.ID as docCreatedByUserID); otherwise created_by must match (caller should only pass createdBy when creator IsProjectUser).

func AuthorizeOwnDocumentRead added in v1.8.12

func AuthorizeOwnDocumentRead(role *models.Role, modelName, userID, createdByID string) error

AuthorizeOwnDocumentRead denies when Read==own and createdByID does not match userID. No-op when Read is not own or the role bypasses data ACL.

func BuildAsyncContext

func BuildAsyncContext(ctx context.Context) (context.Context, context.CancelFunc)

func BuildCRUDPermissions

func BuildCRUDPermissions(modelName string, role *models.Role) (*models.APIPermission, error)

BuildCRUDPermissions is a thin wrapper around EffectivePermission for backward compatibility.

func CamelFromAny added in v1.6.0

func CamelFromAny(modelID string) string

CamelFromAny converts stored model id (canonical snake_case or legacy lowerCamelCase) to lowerCamelCase.

func CamelFromCanonical added in v1.6.0

func CamelFromCanonical(canonical string) string

CamelFromCanonical converts canonical snake_case to lowerCamelCase (e.g. food_order -> foodOrder).

func CanonicalSystemRelationFieldIdentifier added in v1.6.0

func CanonicalSystemRelationFieldIdentifier(identifier string) string

CanonicalSystemRelationFieldIdentifier maps stored schema field ids to the same keys used in document data and connect/disconnect: system_<canonical_model_id>_id or system_<canonical_model_id>_as_<known_as>_id. Legacy schema rows may use mixed casing (e.g. system_foodCategory_id); this normalizes to system_food_category_id.

func CanonicalizeModelName added in v1.6.0

func CanonicalizeModelName(raw string) (string, error)

CanonicalizeModelName normalizes admin input into the canonical snake_case singular model id.

func CaptureInternalServerError

func CaptureInternalServerError(err error, scopes map[string]interface{}) error

func CheckPlanAppUsersQuota added in v1.8.12

func CheckPlanAppUsersQuota(plan *models.Plan, currentCount int) error

CheckPlanAppUsersQuota returns ErrQuotaExceeded when currentCount >= max_app_users.

func CheckPlanRecordsQuota added in v1.8.12

func CheckPlanRecordsQuota(plan *models.Plan, modelName string, currentCount int) error

CheckPlanRecordsQuota returns ErrQuotaExceeded when currentCount >= limit (>0). Limit 0 means unlimited.

func CloneRole added in v1.7.0

func CloneRole(src *models.Role) *models.Role

CloneRole deep-copies a role for duplication. Copied roles are never admin or system-generated.

func CloneRoleKeepingIdentity added in v1.8.12

func CloneRoleKeepingIdentity(src *models.Role) *models.Role

CloneRoleKeepingIdentity deep-copies a role including ID / admin / system flags.

func ComputeReadGraceByModel added in v1.8.12

func ComputeReadGraceByModel(role *models.Role, plan *models.Plan) map[string]bool

ComputeReadGraceByModel returns per-model true when read grace applied under the plan.

func ConnectDisconnectParamBuilder

func ConnectDisconnectParamBuilder(project *models.Project, uid string, connectionIds map[string]interface{}, modelType *models.ModelType) ([]*models.ConnectDisconnectParam, error)

func EffectivePermission added in v1.8.12

func EffectivePermission(role *models.Role, modelName string) *models.APIPermission

EffectivePermission returns the resolved APIPermission for a model.

  • Admin bypass → all/all/all/all
  • demo system role (id=="demo" && SystemGenerated) → read all, mutations none
  • team system role → use LookupAPIPermission or none defaults (NOT blanket all)
  • Do NOT treat SystemGenerated alone as all CRUD
  • Missing model → all none

func ExpandPath added in v1.3.0

func ExpandPath(path string) (string, error)

expandPath expands ~ to home directory and converts to absolute path. If the path starts with ./ or ../, it resolves relative to the current working directory.

func ExtractActionName

func ExtractActionName(name string) string

func ExtractGraphQLOperationName

func ExtractGraphQLOperationName(query string, schema *models.ProjectSchema, isSystemQuery bool) ([]*models.IncomingRequest, error)

func ExtractModelNames

func ExtractModelNames(schema *models.ProjectSchema, queryDoc *ast.QueryDocument) ([]*models.IncomingRequest, bool, error)

func ExtractRelationName

func ExtractRelationName(name string) string

func ExtractResourceName

func ExtractResourceName(name string) string

separate update,delete,create from model name

func FieldIsSortable added in v1.8.8

func FieldIsSortable(f *models.FieldInfo) bool

FieldIsSortable reports whether a top-level model field may appear in public GraphQL list sort payloads and be applied as SQL ORDER BY.

Eligible: text, number, boolean, date, and single-choice fixed list (TEXT column). Not eligible: multiline, media, object, repeated, geo, multi-choice list.

func FilterNumber

func FilterNumber(num string) (string, error)

func FilterProjectArray

func FilterProjectArray(arr *[]*models.Project, key string) *models.Project

FilterProjectArray filters the array by a key and removes the found item from the array

func FilterUserArray

func FilterUserArray(arr *[]*models.SystemUser, key string) *models.SystemUser

FilterUserArray filters the array by a key and removes the found item from the array

func FormatReadableDate added in v1.8.22

func FormatReadableDate(raw, fallback string) string

FormatReadableDate turns RFC3339 / date-only timestamps into "2 January 2006". Empty or unparseable values return fallback (or the raw string if fallback is empty).

func GenerateCombinedQuery

func GenerateCombinedQuery(doc *ast.QueryDocument, fragments map[string]*ast.FragmentDefinition) string

New function to generate the combined output as a single string

func GetCurrentDhakaTime

func GetCurrentDhakaTime() string

func GetCurrentDhakaTimeDateOnly

func GetCurrentDhakaTimeDateOnly() string

func GetCurrentDhakaTimeObject

func GetCurrentDhakaTimeObject() time.Time

func GetCurrentTime

func GetCurrentTime() string

UTC time functions

func GetCurrentTimeObject

func GetCurrentTimeObject() time.Time

func GetDhakaLocation

func GetDhakaLocation() *time.Location

Dhaka time functions

func GetEnv

func GetEnv(key, defaults string) string

func GetGraphQLObject

func GetGraphQLObject(object interface{}) (*graphql.Object, error)

GetGraphQLObject Converts struct into graphql object

func GraphQLComposedTypeName added in v1.6.0

func GraphQLComposedTypeName(modelID string, suffix string) string

GraphQLComposedTypeName builds Tag_Update_Payload style names from model id + suffix (e.g. "Create_Payload", "List_Aggregate", "RawModel").

func GraphQLTypeName added in v1.6.0

func GraphQLTypeName(s string) string

GraphQLTypeName formats a name for GraphQL object/input types. It applies Unicode title case to each underscore-separated segment so compound names match conventional GraphQL PascalCase (e.g. tag_Update_Payload → Tag_Update_Payload). A plain cases.Title on the full string only capitalizes the first rune of the first “word”, which yields Tag_update_payload and breaks clients expecting Tag_Update_Payload.

func GraphQLTypeNameForFilterArg added in v1.6.0

func GraphQLTypeNameForFilterArg(modelID string) string

GraphQLTypeNameForFilterArg is the PascalCase name passed to BuildFilterArgument (list query / count). It matches ListGraphQLTypeName for canonical and legacy ids.

func HTMLToMarkdown added in v1.1.2

func HTMLToMarkdown(html string) string

func HandlePayload

func HandlePayload(model *models.ModelType, data map[string]interface{})

func HandleSubPayload

func HandleSubPayload(field *models.FieldInfo, data map[string]interface{})

func HasMetaQuery

func HasMetaQuery(name string) bool

func IntFormat

func IntFormat(v interface{}) (int, error)

func IntersectAPIPermission added in v1.8.12

func IntersectAPIPermission(roleAP, planAP *models.APIPermission) (out *models.APIPermission, readGrace bool)

IntersectAPIPermission applies the plan ceiling with read-only grace:

create/update/delete = min(role, plan) always
read = min(role, plan) when plan.read != none; otherwise falls back to role.read

Returns the intersected permission and whether read grace applied.

func IntersectLogicExecutions added in v1.8.12

func IntersectLogicExecutions(roleLogic, planLogic []string) []string

IntersectLogicExecutions returns the intersection of role and plan logic lists. A nil/empty plan list or "*" means the role list is unchanged (fully permissive plan).

func IntersectRoleWithPlan added in v1.8.12

func IntersectRoleWithPlan(role *models.Role, plan *models.Plan) *models.Role

IntersectRoleWithPlan clones the role and clamps it under the plan ceiling. Clears IsAdmin so RoleBypassesDataACL no longer wins for tenant app users. Nil plan returns a clone with IsAdmin cleared still? No — nil plan means no ceiling (permissive). Plan with empty api_permissions is treated as fully permissive (seeded "*" style).

func IsCanonicalModelID added in v1.6.0

func IsCanonicalModelID(s string) bool

IsCanonicalModelID reports whether s is already stored canonical form (snake_case ASCII).

func IsInActionNameMap

func IsInActionNameMap(key string) bool

func IsValidIdentifier added in v1.1.4

func IsValidIdentifier(raw string) (*models.ValidIdentifier, error)

IsValidIdentifier normalizes a field label or raw identifier into display label + canonical snake_case id. Word boundaries follow the same rules as CanonicalizeModelName (camelCase, spaces, underscores, hyphens).

func LegacyApplicationCache added in v1.6.0

func LegacyApplicationCache(ctx context.Context) (*models.ApplicationCache, bool)

LegacyApplicationCache returns cache from typed key or legacy string "cache".

func LegacyRelationMeta added in v1.6.0

func LegacyRelationMeta(ctx context.Context) (map[string]interface{}, bool)

LegacyRelationMeta returns relation metadata from typed key or legacy "relation_meta".

func LegacySelectionSet added in v1.6.0

func LegacySelectionSet(ctx context.Context) (ast.SelectionSet, bool)

LegacySelectionSet returns selection set from typed key or legacy "selectionSet".

func LegacyStoredNameToCanonical added in v1.6.0

func LegacyStoredNameToCanonical(stored string) (string, error)

LegacyStoredNameToCanonical converts a legacy stored model name (camelCase or run-on) to canonical snake_case for migration. Does not apply run-on rejection.

func ListGraphQLTypeName added in v1.6.0

func ListGraphQLTypeName(modelID string) string

ListGraphQLTypeName returns the PascalCase list wrapper type (e.g. FoodCategoryList).

func LookupAPIPermission added in v1.6.0

func LookupAPIPermission(role *models.Role, modelName string) (*models.APIPermission, bool)

LookupAPIPermission returns role permissions for a model id (canonical snake or legacy camel key).

func LookupPlanAPIPermission added in v1.8.12

func LookupPlanAPIPermission(plan *models.Plan, modelName string) (*models.APIPermission, bool)

LookupPlanAPIPermission returns plan permissions for a model, falling back to "*" wildcard.

func MarkdownToHTML added in v1.1.2

func MarkdownToHTML(markdown string) string

func MarkdownToText added in v1.1.2

func MarkdownToText(markdown string) string

func MigrateAPIPermissionScopes added in v1.8.12

func MigrateAPIPermissionScopes(ap *models.APIPermission) (changed bool)

MigrateAPIPermissionScopes maps custom_logic → none on each field. Returns whether any field changed.

func MigrateProjectSchemaToNamingV2 added in v1.6.0

func MigrateProjectSchemaToNamingV2(project *models.Project) (bool, error)

MigrateProjectSchemaToNamingV2 rewrites stored model names to canonical snake_case, updates connection references and role API permission keys, and sets NamingSchemaVersion. Returns (true, nil) when the project was modified and should be persisted.

func MigrateRoleAPIPermissions added in v1.8.12

func MigrateRoleAPIPermissions(role *models.Role) int

MigrateRoleAPIPermissions migrates custom_logic scopes on all model permissions. Returns the count of fields migrated.

func MinScope added in v1.8.12

func MinScope(op PermissionOp, a, b string) string

MinScope returns the more restrictive of a and b for the given operation.

func ModelIDMatchesGraphQLField added in v1.6.0

func ModelIDMatchesGraphQLField(storedModelID, graphqlLowerCamel string) bool

ModelIDMatchesGraphQLField reports whether a stored model id matches the lowerCamel resource id used in GraphQL field names.

func ModelSchemaBuilder

func ModelSchemaBuilder(modelType *models.ModelType, update bool) *oas.Schema

func MoveAPIPermissionKey added in v1.8.19

func MoveAPIPermissionKey(perms map[string]*models.APIPermission, oldName, newName string)

MoveAPIPermissionKey renames a permission map entry from oldName to newName. If newName already exists, the old key is dropped so the newer grant wins.

func MultiLineTextFormat

func MultiLineTextFormat(v interface{}) (map[string]interface{}, error)

func MultipleResourceName

func MultipleResourceName(name string) string

func NewID added in v1.6.1

func NewID() string

NewID returns a new lexicographically sortable identifier (ULID string, Crockford base32).

func NewRefreshTokenAuthenticator

func NewRefreshTokenAuthenticator(cfg *models.Config, token string) (*models.JWTTokens, error)

func NormalizeLegacyScope added in v1.8.12

func NormalizeLegacyScope(s string) string

NormalizeLegacyScope maps retired scope values for migration of stored roles. custom_logic → none. Other values are returned unchanged (trimmed).

func OpenApiSpecGenerator

func OpenApiSpecGenerator(env string, loader *models.ApplicationCache) (interface{}, error)

func PascalFromAnyModelID added in v1.6.0

func PascalFromAnyModelID(modelID string) string

PascalFromAnyModelID builds GraphQL PascalCase type names from either canonical snake or legacy camel.

func PascalFromCanonical added in v1.6.0

func PascalFromCanonical(canonical string) string

PascalFromCanonical converts canonical snake_case to PascalCase without underscores (e.g. food_order -> FoodOrder).

func PhysicalSQLTableName added in v1.6.4

func PhysicalSQLTableName(name string) string

PhysicalSQLTableName returns the snake_case model id used for SQL tables, pivot tables, and {model}_id column prefixes. It is aligned with model creation: stored canonical ids (IsCanonicalModelID) are returned unchanged; other input is passed through CanonicalizeModelName, same as admin when creating a model. Do not use for GraphQL field names — use SingularResourceName.

func PlanAllowsLogic added in v1.8.12

func PlanAllowsLogic(plan *models.Plan, fn string) bool

PlanAllowsLogic reports whether a plan permits a logic/function execution. Empty LogicExecutions or "*" entry means fully permissive.

func PlanQuotaLimit added in v1.8.12

func PlanQuotaLimit(plan *models.Plan, key string) int

PlanQuotaLimit returns the numeric quota for key, or 0 when unlimited / missing.

func PostgresProjectSchemaName added in v1.6.1

func PostgresProjectSchemaName(projectID string) string

PostgresProjectSchemaName returns a safe PostgreSQL identifier for per-project schema isolation (GENERAL_POSTGRES_ISOLATION=schema). Prefix "p_" plus sanitized project id; max length 63 (PG limit).

func ProcessMultilineField added in v1.1.2

func ProcessMultilineField(input map[string]interface{}) map[string]interface{}

Convenience functions using the default processor

func RandomNumberGenerator

func RandomNumberGenerator(min, max int) string

func RandomStringGenerator

func RandomStringGenerator(n int) string

func RandomVariableGenerator

func RandomVariableGenerator(n int) string

func RecordsQuotaKey added in v1.8.12

func RecordsQuotaKey(modelName string) string

RecordsQuotaKey builds max_records.<model> quota key.

func RelationFilterGraphQLKey added in v1.7.7

func RelationFilterGraphQLKey(modelName, knownAs string) string

RelationFilterGraphQLKey is the public GraphQL key for relation list filters and nested has_one relation fields. When known_as is set it is the field alias (e.g. owner); otherwise the canonical stored model id (snake_case, e.g. food_category). Query roots like foodCategoryList stay lowerCamel via SingularResourceName / MultipleResourceName.

func RelationMetaFromContext added in v1.6.0

func RelationMetaFromContext(ctx context.Context) (map[string]interface{}, bool)

RelationMetaFromContext returns relation metadata from ctx.

func RelationNestedListGraphQLKey added in v1.8.6

func RelationNestedListGraphQLKey(modelName, knownAs string) string

RelationNestedListGraphQLKey is the nested has_many field on a parent type (e.g. food_category_list, chef_list). Fully snake_case — only root query/mutation operation names use lowerCamel (MultipleResourceName → foodCategoryList).

func ResolveStoredModelID added in v1.6.0

func ResolveStoredModelID(knownIDs map[string]bool, graphqlSingular string) string

ResolveStoredModelID maps a GraphQL singular base name (e.g. foodCategory from foodCategoryList, or food_category) to the project schema's stored model id (e.g. food_category). knownIDs keys are Model.Name values. Matches exact id or the same CamelFromAny identity.

func RewriteProjectPermissionKeys added in v1.8.19

func RewriteProjectPermissionKeys(project *models.Project, oldName, newName string)

RewriteProjectPermissionKeys updates role and plan API permission keys after a model rename. Public GraphQL hides relation fields (e.g. variant_list) when the staff role still grants the old model id (tag) and the schema now uses the new id (variant).

func RoleBypassesDataACL added in v1.8.12

func RoleBypassesDataACL(role *models.Role) bool

RoleBypassesDataACL is true for project admin (IsAdmin or id admin/owner), unless a tenant plan ceiling has been applied (PlanClamped).

func SQLiteProjectFileName added in v1.6.1

func SQLiteProjectFileName(projectID string) string

SQLiteProjectFileName returns a filename under DefaultDatabaseDir for per-project SQLite files (GENERAL_SQLITE_FILE_PER_PROJECT). Must end with .sqlite for GetSQLDriver validation.

func SanitizeMarkdown added in v1.1.2

func SanitizeMarkdown(markdown string) string

func ScopeRank added in v1.8.12

func ScopeRank(op PermissionOp, scope string) int

ScopeRank returns the ordinal of a scope for the given operation. Lattice: none < own < auth < all. Create has no own (own ranks as none).

func SelectionSetFromContext added in v1.6.0

func SelectionSetFromContext(ctx context.Context) (ast.SelectionSet, bool)

SelectionSetFromContext returns the selection set from ctx.

func SetTokenClaimsToRouter

func SetTokenClaimsToRouter(ctx echo.Context, tokenClaims *models.TokenClaims) error

func SetTokenCookie

func SetTokenCookie(cfg *models.Config, name, token string, httpOnly bool, expire bool) *http.Cookie

func SingularResourceName

func SingularResourceName(name string) string

SingularResourceName returns the lowerCamelCase singular resource id for GraphQL fields. It accepts canonical snake_case model ids, legacy camelCase ids, or field names ending in List / ListCount.

func SyntheticSystemRelationFieldIdentifier added in v1.6.4

func SyntheticSystemRelationFieldIdentifier(modelID, knownAs string) string

SyntheticSystemRelationFieldIdentifier builds system_<canonical_model>_id or system_<canonical_model>_as_<known_as>_id for schema-stored synthetic relation fields. Segments use PhysicalSQLTableName so they align with SQL FK columns. Do not use raw Connection.Model in fmt.Sprintf — lowerCamel or collapsed lowercase breaks SQLite column names.

func ValidateCreateScope added in v1.8.12

func ValidateCreateScope(p interface{}) (*string, bool)

ValidateCreateScope accepts none | all | auth (rejects own and custom_logic).

func ValidateDeleteScope added in v1.8.12

func ValidateDeleteScope(p interface{}) (*string, bool)

ValidateDeleteScope accepts none | all | auth | own.

func ValidatePermissions

func ValidatePermissions(vv map[string]interface{}) (*models.APIPermission, error)

func ValidateReadScope added in v1.8.12

func ValidateReadScope(p interface{}) (*string, bool)

ValidateReadScope accepts none | all | auth | own.

func ValidateScope

func ValidateScope(p interface{}) (*string, bool)

ValidateScope accepts permission scope strings for read/update/delete-compatible sets. Prefer operation-aware validators. custom_logic is rejected.

func ValidateUpdateScope added in v1.8.12

func ValidateUpdateScope(p interface{}) (*string, bool)

ValidateUpdateScope accepts none | all | auth | own.

func WhereFilterConditionGraphQLTypeName added in v1.7.0

func WhereFilterConditionGraphQLTypeName(modelName, fieldIdentifier string) string

WhereFilterConditionGraphQLTypeName returns a unique GraphQL input type for per-field where filters. Model and field are separate segments so loan.installment_amount and loan_installment.amount do not collide.

func WithApplicationCache added in v1.6.0

func WithApplicationCache(ctx context.Context, c *models.ApplicationCache) context.Context

WithApplicationCache attaches the application cache to ctx.

func WithRelationMeta added in v1.6.0

func WithRelationMeta(ctx context.Context, meta map[string]interface{}) context.Context

WithRelationMeta attaches relation metadata for dataloaders (replaces string key "relation_meta").

func WithSelectionSet added in v1.6.0

func WithSelectionSet(ctx context.Context, sel ast.SelectionSet) context.Context

WithSelectionSet attaches the root GraphQL selection set (for relation resolution).

Types

type Authenticator

type Authenticator struct {
	Provider *oidc.Provider
	Config   oauth2.Config
	Ctx      context.Context
}

func NewAuthenticator

func NewAuthenticator(cfg *models.Config) (*Authenticator, error)

type CRUDPermissions

type CRUDPermissions struct {
	Create bool
	Read   bool
	Update bool
	Delete bool
}

type GoroutineMonitor added in v1.1.0

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

func NewGoroutineMonitor added in v1.1.0

func NewGoroutineMonitor() *GoroutineMonitor

func (*GoroutineMonitor) GetCurrentCount added in v1.1.0

func (gm *GoroutineMonitor) GetCurrentCount() int

func (*GoroutineMonitor) StartMonitoring added in v1.1.0

func (gm *GoroutineMonitor) StartMonitoring(ctx context.Context)

func (*GoroutineMonitor) StopMonitoring added in v1.1.0

func (gm *GoroutineMonitor) StopMonitoring()

type MarkdownProcessor added in v1.1.2

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

MarkdownProcessor handles markdown sanitization and conversion

func NewMarkdownProcessor added in v1.1.2

func NewMarkdownProcessor() *MarkdownProcessor

NewMarkdownProcessor creates a new markdown processor with proper sanitization

func (*MarkdownProcessor) HTMLToMarkdown added in v1.1.2

func (mp *MarkdownProcessor) HTMLToMarkdown(html string) string

HTMLToMarkdown converts HTML to markdown

func (*MarkdownProcessor) MarkdownToHTML added in v1.1.2

func (mp *MarkdownProcessor) MarkdownToHTML(markdown string) string

MarkdownToHTML converts markdown to sanitized HTML

func (*MarkdownProcessor) MarkdownToText added in v1.1.2

func (mp *MarkdownProcessor) MarkdownToText(markdown string) string

MarkdownToText converts markdown to plain text (removes all formatting)

func (*MarkdownProcessor) ProcessMultilineField added in v1.1.2

func (mp *MarkdownProcessor) ProcessMultilineField(input map[string]interface{}) map[string]interface{}

ProcessMultilineField processes a multiline field with markdown as the source of truth

func (*MarkdownProcessor) SanitizeMarkdown added in v1.1.2

func (mp *MarkdownProcessor) SanitizeMarkdown(markdown string) string

SanitizeMarkdown removes potentially dangerous content from markdown

func (*MarkdownProcessor) TextToMarkdown added in v1.1.2

func (mp *MarkdownProcessor) TextToMarkdown(text string) string

TextToMarkdown converts plain text to basic markdown

type NamingV2ModelRenamePair added in v1.6.0

type NamingV2ModelRenamePair struct {
	Old string
	New string
}

NamingV2ModelRenamePair is one model identifier change produced by naming schema V2 migration.

func ComputeNamingV2ModelRenamePairs added in v1.6.0

func ComputeNamingV2ModelRenamePairs(project *models.Project) ([]NamingV2ModelRenamePair, error)

ComputeNamingV2ModelRenamePairs returns rename pairs for a project still on legacy naming. When the project is already on naming V2, or has no schema, it returns (nil, nil).

type NamingV2PhysicalMigrator added in v1.6.0

type NamingV2PhysicalMigrator interface {
	ApplyNamingV2PhysicalMigration(ctx context.Context, projectID string, pairs []NamingV2ModelRenamePair, perModelCollections bool, relationTenantModel string) error
}

NamingV2PhysicalMigrator is implemented by project database drivers that can rewrite persisted rows (for example Arango document `type` and collection names) before the in-memory schema is migrated. relationTenantModel is the SaaS tenant root model name (e.g. "restaurant"); when non-empty, relation edges that still carry root-level tenant_id are rewritten into ext (tenant_id, tenant_model).

type PermissionOp added in v1.8.12

type PermissionOp string

PermissionOp identifies a CRUD operation for scope ranking / min.

const (
	OpRead   PermissionOp = "read"
	OpCreate PermissionOp = "create"
	OpUpdate PermissionOp = "update"
	OpDelete PermissionOp = "delete"
)

type RESTtoGraphResponse

type RESTtoGraphResponse struct {
	Query         string `json:"query"`
	QueryName     string `json:"query_name"`
	OperationName string `json:"operation_name"`
}

func HandleFunctionGraphqlBase

func HandleFunctionGraphqlBase(c echo.Context, schema *models.ProjectSchema, functionName string) (*RESTtoGraphResponse, error)

func RESTtoGraphQL

func RESTtoGraphQL(c echo.Context, schema *models.ProjectSchema, rootModel string, rest url.Values, skipQueryDef bool) (*RESTtoGraphResponse, error)

Jump to

Keyboard shortcuts

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