utility

package
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: Apache-2.0 Imports: 42 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
)

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",
	"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",
	"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 BuildAsyncContext

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

func BuildCRUDPermissions

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

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 ConnectDisconnectParamBuilder

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

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 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 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 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(identifier string) (*models.ValidIdentifier, error)

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 MarkdownToHTML added in v1.1.2

func MarkdownToHTML(markdown string) string

func MarkdownToText added in v1.1.2

func MarkdownToText(markdown string) string

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 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 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 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 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 RelationMetaFromContext added in v1.6.0

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

RelationMetaFromContext returns relation metadata from ctx.

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 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 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 ValidatePermissions

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

func ValidateScope

func ValidateScope(p string) (*string, bool)

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 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