mirror of
https://github.com/bitechdev/ResolveSpec.git
synced 2026-01-12 05:54:25 +00:00
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb20a354fc | ||
|
|
37c85361ba | ||
|
|
a7e640a6a1 | ||
|
|
bf7125efc3 | ||
|
|
e220ab3d34 | ||
|
|
6a0297713a | ||
|
|
6ea200bb2b | ||
|
|
987244019c |
@@ -3,6 +3,8 @@ package common
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CORSConfig holds CORS configuration
|
// CORSConfig holds CORS configuration
|
||||||
@@ -15,8 +17,30 @@ type CORSConfig struct {
|
|||||||
|
|
||||||
// DefaultCORSConfig returns a default CORS configuration suitable for HeadSpec
|
// DefaultCORSConfig returns a default CORS configuration suitable for HeadSpec
|
||||||
func DefaultCORSConfig() CORSConfig {
|
func DefaultCORSConfig() CORSConfig {
|
||||||
|
configManager := config.GetConfigManager()
|
||||||
|
cfg, _ := configManager.GetConfig()
|
||||||
|
hosts := make([]string, 0)
|
||||||
|
// hosts = append(hosts, "*")
|
||||||
|
|
||||||
|
_, _, ipsList := config.GetIPs()
|
||||||
|
|
||||||
|
for i := range cfg.Servers.Instances {
|
||||||
|
server := cfg.Servers.Instances[i]
|
||||||
|
if server.Port == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
hosts = append(hosts, server.ExternalURLs...)
|
||||||
|
hosts = append(hosts, fmt.Sprintf("http://%s:%d", server.Host, server.Port))
|
||||||
|
hosts = append(hosts, fmt.Sprintf("https://%s:%d", server.Host, server.Port))
|
||||||
|
hosts = append(hosts, fmt.Sprintf("http://%s:%d", "localhost", server.Port))
|
||||||
|
for _, ip := range ipsList {
|
||||||
|
hosts = append(hosts, fmt.Sprintf("http://%s:%d", ip.String(), server.Port))
|
||||||
|
hosts = append(hosts, fmt.Sprintf("https://%s:%d", ip.String(), server.Port))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return CORSConfig{
|
return CORSConfig{
|
||||||
AllowedOrigins: []string{"*"},
|
AllowedOrigins: hosts,
|
||||||
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||||
AllowedHeaders: GetHeadSpecHeaders(),
|
AllowedHeaders: GetHeadSpecHeaders(),
|
||||||
MaxAge: 86400, // 24 hours
|
MaxAge: 86400, // 24 hours
|
||||||
@@ -90,11 +114,14 @@ func GetHeadSpecHeaders() []string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetCORSHeaders sets CORS headers on a response writer
|
// SetCORSHeaders sets CORS headers on a response writer
|
||||||
func SetCORSHeaders(w ResponseWriter, config CORSConfig) {
|
func SetCORSHeaders(w ResponseWriter, r Request, config CORSConfig) {
|
||||||
// Set allowed origins
|
// Set allowed origins
|
||||||
if len(config.AllowedOrigins) > 0 {
|
// if len(config.AllowedOrigins) > 0 {
|
||||||
w.SetHeader("Access-Control-Allow-Origin", strings.Join(config.AllowedOrigins, ", "))
|
// w.SetHeader("Access-Control-Allow-Origin", strings.Join(config.AllowedOrigins, ", "))
|
||||||
}
|
// }
|
||||||
|
|
||||||
|
// Todo origin list parsing
|
||||||
|
w.SetHeader("Access-Control-Allow-Origin", "*")
|
||||||
|
|
||||||
// Set allowed methods
|
// Set allowed methods
|
||||||
if len(config.AllowedMethods) > 0 {
|
if len(config.AllowedMethods) > 0 {
|
||||||
@@ -102,9 +129,10 @@ func SetCORSHeaders(w ResponseWriter, config CORSConfig) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set allowed headers
|
// Set allowed headers
|
||||||
if len(config.AllowedHeaders) > 0 {
|
// if len(config.AllowedHeaders) > 0 {
|
||||||
w.SetHeader("Access-Control-Allow-Headers", strings.Join(config.AllowedHeaders, ", "))
|
// w.SetHeader("Access-Control-Allow-Headers", strings.Join(config.AllowedHeaders, ", "))
|
||||||
}
|
// }
|
||||||
|
w.SetHeader("Access-Control-Allow-Headers", "*")
|
||||||
|
|
||||||
// Set max age
|
// Set max age
|
||||||
if config.MaxAge > 0 {
|
if config.MaxAge > 0 {
|
||||||
@@ -115,5 +143,7 @@ func SetCORSHeaders(w ResponseWriter, config CORSConfig) {
|
|||||||
w.SetHeader("Access-Control-Allow-Credentials", "true")
|
w.SetHeader("Access-Control-Allow-Credentials", "true")
|
||||||
|
|
||||||
// Expose headers that clients can read
|
// Expose headers that clients can read
|
||||||
w.SetHeader("Access-Control-Expose-Headers", "Content-Range, X-Api-Range-Total, X-Api-Range-Size")
|
exposeHeaders := config.AllowedHeaders
|
||||||
|
exposeHeaders = append(exposeHeaders, "Content-Range", "X-Api-Range-Total", "X-Api-Range-Size")
|
||||||
|
w.SetHeader("Access-Control-Expose-Headers", strings.Join(exposeHeaders, ", "))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ package common
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ValidateAndUnwrapModelResult contains the result of model validation
|
// ValidateAndUnwrapModelResult contains the result of model validation
|
||||||
@@ -45,3 +48,216 @@ func ValidateAndUnwrapModel(model interface{}) (*ValidateAndUnwrapModelResult, e
|
|||||||
OriginalType: originalType,
|
OriginalType: originalType,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ExtractTagValue extracts the value for a given key from a struct tag string.
|
||||||
|
// It handles both semicolon and comma-separated tag formats (e.g., GORM and BUN tags).
|
||||||
|
// For tags like "json:name;validate:required" it will extract "name" for key "json".
|
||||||
|
// For tags like "rel:has-many,join:table" it will extract "table" for key "join".
|
||||||
|
func ExtractTagValue(tag, key string) string {
|
||||||
|
// Split by both semicolons and commas to handle different tag formats
|
||||||
|
// We need to be smart about this - commas can be part of values
|
||||||
|
// So we'll try semicolon first, then comma if needed
|
||||||
|
separators := []string{";", ","}
|
||||||
|
|
||||||
|
for _, sep := range separators {
|
||||||
|
parts := strings.Split(tag, sep)
|
||||||
|
for _, part := range parts {
|
||||||
|
part = strings.TrimSpace(part)
|
||||||
|
if strings.HasPrefix(part, key+":") {
|
||||||
|
return strings.TrimPrefix(part, key+":")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRelationshipInfo analyzes a model type and extracts relationship metadata
|
||||||
|
// for a specific relation field identified by its JSON name.
|
||||||
|
// Returns nil if the field is not found or is not a valid relationship.
|
||||||
|
func GetRelationshipInfo(modelType reflect.Type, relationName string) *RelationshipInfo {
|
||||||
|
// Ensure we have a struct type
|
||||||
|
if modelType == nil || modelType.Kind() != reflect.Struct {
|
||||||
|
logger.Warn("Cannot get relationship info from non-struct type: %v", modelType)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < modelType.NumField(); i++ {
|
||||||
|
field := modelType.Field(i)
|
||||||
|
jsonTag := field.Tag.Get("json")
|
||||||
|
jsonName := strings.Split(jsonTag, ",")[0]
|
||||||
|
|
||||||
|
if jsonName == relationName {
|
||||||
|
gormTag := field.Tag.Get("gorm")
|
||||||
|
bunTag := field.Tag.Get("bun")
|
||||||
|
info := &RelationshipInfo{
|
||||||
|
FieldName: field.Name,
|
||||||
|
JSONName: jsonName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(bunTag, "rel:") || strings.Contains(bunTag, "join:") {
|
||||||
|
//bun:"rel:has-many,join:rid_hub=rid_hub_division"
|
||||||
|
if strings.Contains(bunTag, "has-many") {
|
||||||
|
info.RelationType = "hasMany"
|
||||||
|
} else if strings.Contains(bunTag, "has-one") {
|
||||||
|
info.RelationType = "hasOne"
|
||||||
|
} else if strings.Contains(bunTag, "belongs-to") {
|
||||||
|
info.RelationType = "belongsTo"
|
||||||
|
} else if strings.Contains(bunTag, "many-to-many") {
|
||||||
|
info.RelationType = "many2many"
|
||||||
|
} else {
|
||||||
|
info.RelationType = "hasOne"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract join info
|
||||||
|
joinPart := ExtractTagValue(bunTag, "join")
|
||||||
|
if joinPart != "" && info.RelationType == "many2many" {
|
||||||
|
// For many2many, the join part is the join table name
|
||||||
|
info.JoinTable = joinPart
|
||||||
|
} else if joinPart != "" {
|
||||||
|
// For other relations, parse foreignKey and references
|
||||||
|
joinParts := strings.Split(joinPart, "=")
|
||||||
|
if len(joinParts) == 2 {
|
||||||
|
info.ForeignKey = joinParts[0]
|
||||||
|
info.References = joinParts[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get related model type
|
||||||
|
if field.Type.Kind() == reflect.Slice {
|
||||||
|
elemType := field.Type.Elem()
|
||||||
|
if elemType.Kind() == reflect.Ptr {
|
||||||
|
elemType = elemType.Elem()
|
||||||
|
}
|
||||||
|
if elemType.Kind() == reflect.Struct {
|
||||||
|
info.RelatedModel = reflect.New(elemType).Elem().Interface()
|
||||||
|
}
|
||||||
|
} else if field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Struct {
|
||||||
|
elemType := field.Type
|
||||||
|
if elemType.Kind() == reflect.Ptr {
|
||||||
|
elemType = elemType.Elem()
|
||||||
|
}
|
||||||
|
if elemType.Kind() == reflect.Struct {
|
||||||
|
info.RelatedModel = reflect.New(elemType).Elem().Interface()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse GORM tag to determine relationship type and keys
|
||||||
|
if strings.Contains(gormTag, "foreignKey") {
|
||||||
|
info.ForeignKey = ExtractTagValue(gormTag, "foreignKey")
|
||||||
|
info.References = ExtractTagValue(gormTag, "references")
|
||||||
|
|
||||||
|
// Determine if it's belongsTo or hasMany/hasOne
|
||||||
|
if field.Type.Kind() == reflect.Slice {
|
||||||
|
info.RelationType = "hasMany"
|
||||||
|
// Get the element type for slice
|
||||||
|
elemType := field.Type.Elem()
|
||||||
|
if elemType.Kind() == reflect.Ptr {
|
||||||
|
elemType = elemType.Elem()
|
||||||
|
}
|
||||||
|
if elemType.Kind() == reflect.Struct {
|
||||||
|
info.RelatedModel = reflect.New(elemType).Elem().Interface()
|
||||||
|
}
|
||||||
|
} else if field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Struct {
|
||||||
|
info.RelationType = "belongsTo"
|
||||||
|
elemType := field.Type
|
||||||
|
if elemType.Kind() == reflect.Ptr {
|
||||||
|
elemType = elemType.Elem()
|
||||||
|
}
|
||||||
|
if elemType.Kind() == reflect.Struct {
|
||||||
|
info.RelatedModel = reflect.New(elemType).Elem().Interface()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if strings.Contains(gormTag, "many2many") {
|
||||||
|
info.RelationType = "many2many"
|
||||||
|
info.JoinTable = ExtractTagValue(gormTag, "many2many")
|
||||||
|
// Get the element type for many2many (always slice)
|
||||||
|
if field.Type.Kind() == reflect.Slice {
|
||||||
|
elemType := field.Type.Elem()
|
||||||
|
if elemType.Kind() == reflect.Ptr {
|
||||||
|
elemType = elemType.Elem()
|
||||||
|
}
|
||||||
|
if elemType.Kind() == reflect.Struct {
|
||||||
|
info.RelatedModel = reflect.New(elemType).Elem().Interface()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Field has no GORM relationship tags, so it's not a relation
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RelationPathToBunAlias converts a relation path (e.g., "Order.Customer") to a Bun alias format.
|
||||||
|
// It converts to lowercase and replaces dots with double underscores.
|
||||||
|
// For example: "Order.Customer" -> "order__customer"
|
||||||
|
func RelationPathToBunAlias(relationPath string) string {
|
||||||
|
if relationPath == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
// Convert to lowercase and replace dots with double underscores
|
||||||
|
alias := strings.ToLower(relationPath)
|
||||||
|
alias = strings.ReplaceAll(alias, ".", "__")
|
||||||
|
return alias
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplaceTableReferencesInSQL replaces references to a base table name in a SQL expression
|
||||||
|
// with the appropriate alias for the current preload level.
|
||||||
|
// For example, if baseTableName is "mastertaskitem" and targetAlias is "mal__mal",
|
||||||
|
// it will replace "mastertaskitem.rid_mastertaskitem" with "mal__mal.rid_mastertaskitem"
|
||||||
|
func ReplaceTableReferencesInSQL(sqlExpr, baseTableName, targetAlias string) string {
|
||||||
|
if sqlExpr == "" || baseTableName == "" || targetAlias == "" {
|
||||||
|
return sqlExpr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace both quoted and unquoted table references
|
||||||
|
// Handle patterns like: tablename.column, "tablename".column, tablename."column", "tablename"."column"
|
||||||
|
|
||||||
|
// Pattern 1: tablename.column (unquoted)
|
||||||
|
result := strings.ReplaceAll(sqlExpr, baseTableName+".", targetAlias+".")
|
||||||
|
|
||||||
|
// Pattern 2: "tablename".column or "tablename"."column" (quoted table name)
|
||||||
|
result = strings.ReplaceAll(result, "\""+baseTableName+"\".", "\""+targetAlias+"\".")
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTableNameFromModel extracts the table name from a model.
|
||||||
|
// It checks the bun tag first, then falls back to converting the struct name to snake_case.
|
||||||
|
func GetTableNameFromModel(model interface{}) string {
|
||||||
|
if model == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
modelType := reflect.TypeOf(model)
|
||||||
|
|
||||||
|
// Unwrap pointers
|
||||||
|
for modelType != nil && modelType.Kind() == reflect.Ptr {
|
||||||
|
modelType = modelType.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if modelType == nil || modelType.Kind() != reflect.Struct {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Look for bun tag on embedded BaseModel
|
||||||
|
for i := 0; i < modelType.NumField(); i++ {
|
||||||
|
field := modelType.Field(i)
|
||||||
|
if field.Anonymous {
|
||||||
|
bunTag := field.Tag.Get("bun")
|
||||||
|
if strings.HasPrefix(bunTag, "table:") {
|
||||||
|
return strings.TrimPrefix(bunTag, "table:")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: convert struct name to lowercase (simple heuristic)
|
||||||
|
// This handles cases like "MasterTaskItem" -> "mastertaskitem"
|
||||||
|
return strings.ToLower(modelType.Name())
|
||||||
|
}
|
||||||
|
|||||||
108
pkg/common/handler_utils_test.go
Normal file
108
pkg/common/handler_utils_test.go
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExtractTagValue(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
tag string
|
||||||
|
key string
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "Extract existing key",
|
||||||
|
tag: "json:name;validate:required",
|
||||||
|
key: "json",
|
||||||
|
expected: "name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract key with spaces",
|
||||||
|
tag: "json:name ; validate:required",
|
||||||
|
key: "validate",
|
||||||
|
expected: "required",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract key at end",
|
||||||
|
tag: "json:name;validate:required;db:column_name",
|
||||||
|
key: "db",
|
||||||
|
expected: "column_name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract key at beginning",
|
||||||
|
tag: "primary:true;json:id;db:user_id",
|
||||||
|
key: "primary",
|
||||||
|
expected: "true",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Key not found",
|
||||||
|
tag: "json:name;validate:required",
|
||||||
|
key: "db",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Empty tag",
|
||||||
|
tag: "",
|
||||||
|
key: "json",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Single key-value pair",
|
||||||
|
tag: "json:name",
|
||||||
|
key: "json",
|
||||||
|
expected: "name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Key with empty value",
|
||||||
|
tag: "json:;validate:required",
|
||||||
|
key: "json",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Key with complex value",
|
||||||
|
tag: "json:user_name,omitempty;validate:required,min=3",
|
||||||
|
key: "json",
|
||||||
|
expected: "user_name,omitempty",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Multiple semicolons",
|
||||||
|
tag: "json:name;;validate:required",
|
||||||
|
key: "validate",
|
||||||
|
expected: "required",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "BUN Tag with comma separator",
|
||||||
|
tag: "rel:has-many,join:rid_hub=rid_hub_child",
|
||||||
|
key: "join",
|
||||||
|
expected: "rid_hub=rid_hub_child",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract foreignKey",
|
||||||
|
tag: "foreignKey:UserID;references:ID",
|
||||||
|
key: "foreignKey",
|
||||||
|
expected: "UserID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract references",
|
||||||
|
tag: "foreignKey:UserID;references:ID",
|
||||||
|
key: "references",
|
||||||
|
expected: "ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract many2many",
|
||||||
|
tag: "many2many:user_roles",
|
||||||
|
key: "many2many",
|
||||||
|
expected: "user_roles",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result := ExtractTagValue(tt.tag, tt.key)
|
||||||
|
if result != tt.expected {
|
||||||
|
t.Errorf("ExtractTagValue(%q, %q) = %q; want %q", tt.tag, tt.key, result, tt.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,17 +20,6 @@ type RelationshipInfoProvider interface {
|
|||||||
GetRelationshipInfo(modelType reflect.Type, relationName string) *RelationshipInfo
|
GetRelationshipInfo(modelType reflect.Type, relationName string) *RelationshipInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
// RelationshipInfo contains information about a model relationship
|
|
||||||
type RelationshipInfo struct {
|
|
||||||
FieldName string
|
|
||||||
JSONName string
|
|
||||||
RelationType string // "belongsTo", "hasMany", "hasOne", "many2many"
|
|
||||||
ForeignKey string
|
|
||||||
References string
|
|
||||||
JoinTable string
|
|
||||||
RelatedModel interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NestedCUDProcessor handles recursive processing of nested object graphs
|
// NestedCUDProcessor handles recursive processing of nested object graphs
|
||||||
type NestedCUDProcessor struct {
|
type NestedCUDProcessor struct {
|
||||||
db Database
|
db Database
|
||||||
@@ -218,9 +207,9 @@ func (p *NestedCUDProcessor) processInsert(
|
|||||||
for key, value := range data {
|
for key, value := range data {
|
||||||
query = query.Value(key, value)
|
query = query.Value(key, value)
|
||||||
}
|
}
|
||||||
|
pkName := reflection.GetPrimaryKeyName(tableName)
|
||||||
// Add RETURNING clause to get the inserted ID
|
// Add RETURNING clause to get the inserted ID
|
||||||
query = query.Returning("id")
|
query = query.Returning(pkName)
|
||||||
|
|
||||||
result, err := query.Exec(ctx)
|
result, err := query.Exec(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -231,8 +220,8 @@ func (p *NestedCUDProcessor) processInsert(
|
|||||||
var id interface{}
|
var id interface{}
|
||||||
if lastID, err := result.LastInsertId(); err == nil && lastID > 0 {
|
if lastID, err := result.LastInsertId(); err == nil && lastID > 0 {
|
||||||
id = lastID
|
id = lastID
|
||||||
} else if data["id"] != nil {
|
} else if data[pkName] != nil {
|
||||||
id = data["id"]
|
id = data[pkName]
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Debug("Insert successful, ID: %v, rows affected: %d", id, result.RowsAffected())
|
logger.Debug("Insert successful, ID: %v, rows affected: %d", id, result.RowsAffected())
|
||||||
|
|||||||
@@ -111,3 +111,14 @@ type TableMetadata struct {
|
|||||||
Columns []Column `json:"columns"`
|
Columns []Column `json:"columns"`
|
||||||
Relations []string `json:"relations"`
|
Relations []string `json:"relations"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RelationshipInfo contains information about a model relationship
|
||||||
|
type RelationshipInfo struct {
|
||||||
|
FieldName string `json:"field_name"`
|
||||||
|
JSONName string `json:"json_name"`
|
||||||
|
RelationType string `json:"relation_type"` // "belongsTo", "hasMany", "hasOne", "many2many"
|
||||||
|
ForeignKey string `json:"foreign_key"`
|
||||||
|
References string `json:"references"`
|
||||||
|
JoinTable string `json:"join_table"`
|
||||||
|
RelatedModel interface{} `json:"related_model"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -73,6 +73,9 @@ type ServerInstanceConfig struct {
|
|||||||
|
|
||||||
// Tags for organization and filtering
|
// Tags for organization and filtering
|
||||||
Tags map[string]string `mapstructure:"tags"`
|
Tags map[string]string `mapstructure:"tags"`
|
||||||
|
|
||||||
|
// ExternalURLs are additional URLs that this server instance is accessible from (for CORS) for proxy setups
|
||||||
|
ExternalURLs []string `mapstructure:"external_urls"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TracingConfig holds OpenTelemetry tracing configuration
|
// TracingConfig holds OpenTelemetry tracing configuration
|
||||||
|
|||||||
@@ -12,6 +12,16 @@ type Manager struct {
|
|||||||
v *viper.Viper
|
v *viper.Viper
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var configInstance *Manager
|
||||||
|
|
||||||
|
// GetConfigManager returns a singleton configuration manager instance
|
||||||
|
func GetConfigManager() *Manager {
|
||||||
|
if configInstance == nil {
|
||||||
|
configInstance = NewManager()
|
||||||
|
}
|
||||||
|
return configInstance
|
||||||
|
}
|
||||||
|
|
||||||
// NewManager creates a new configuration manager with defaults
|
// NewManager creates a new configuration manager with defaults
|
||||||
func NewManager() *Manager {
|
func NewManager() *Manager {
|
||||||
v := viper.New()
|
v := viper.New()
|
||||||
@@ -32,7 +42,8 @@ func NewManager() *Manager {
|
|||||||
// Set default values
|
// Set default values
|
||||||
setDefaults(v)
|
setDefaults(v)
|
||||||
|
|
||||||
return &Manager{v: v}
|
configInstance = &Manager{v: v}
|
||||||
|
return configInstance
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewManagerWithOptions creates a new configuration manager with custom options
|
// NewManagerWithOptions creates a new configuration manager with custom options
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ApplyGlobalDefaults applies global server defaults to this instance
|
// ApplyGlobalDefaults applies global server defaults to this instance
|
||||||
@@ -105,3 +108,42 @@ func (sc *ServersConfig) GetDefault() (*ServerInstanceConfig, error) {
|
|||||||
|
|
||||||
return &instance, nil
|
return &instance, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetIPs - GetIP for pc
|
||||||
|
func GetIPs() (hostname string, ipList string, ipNetList []net.IP) {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
fmt.Println("Recovered in GetIPs", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
hostname, _ = os.Hostname()
|
||||||
|
ipaddrlist := make([]net.IP, 0)
|
||||||
|
iplist := ""
|
||||||
|
addrs, err := net.LookupIP(hostname)
|
||||||
|
if err != nil {
|
||||||
|
return hostname, iplist, ipaddrlist
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, a := range addrs {
|
||||||
|
// cfg.LogInfo("\nFound IP Host Address: %s", a)
|
||||||
|
if strings.Contains(a.String(), "127.0.0.1") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
iplist = fmt.Sprintf("%s,%s", iplist, a)
|
||||||
|
ipaddrlist = append(ipaddrlist, a)
|
||||||
|
}
|
||||||
|
if iplist == "" {
|
||||||
|
iff, _ := net.InterfaceAddrs()
|
||||||
|
for _, a := range iff {
|
||||||
|
// cfg.LogInfo("\nFound IP Address: %s", a)
|
||||||
|
if strings.Contains(a.String(), "127.0.0.1") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
iplist = fmt.Sprintf("%s,%s", iplist, a)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
iplist = strings.TrimLeft(iplist, ",")
|
||||||
|
return hostname, iplist, ipaddrlist
|
||||||
|
}
|
||||||
|
|||||||
@@ -584,11 +584,23 @@ func ExtractSourceColumn(colName string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToSnakeCase converts a string from CamelCase to snake_case
|
// ToSnakeCase converts a string from CamelCase to snake_case
|
||||||
|
// Handles consecutive uppercase letters (acronyms) correctly:
|
||||||
|
// "HTTPServer" -> "http_server", "UserID" -> "user_id", "MyHTTPServer" -> "my_http_server"
|
||||||
func ToSnakeCase(s string) string {
|
func ToSnakeCase(s string) string {
|
||||||
var result strings.Builder
|
var result strings.Builder
|
||||||
for i, r := range s {
|
runes := []rune(s)
|
||||||
|
|
||||||
|
for i, r := range runes {
|
||||||
if i > 0 && r >= 'A' && r <= 'Z' {
|
if i > 0 && r >= 'A' && r <= 'Z' {
|
||||||
result.WriteRune('_')
|
// Add underscore if:
|
||||||
|
// 1. Previous character is lowercase, OR
|
||||||
|
// 2. Next character is lowercase (transition from acronym to word)
|
||||||
|
prevIsLower := runes[i-1] >= 'a' && runes[i-1] <= 'z'
|
||||||
|
nextIsLower := i+1 < len(runes) && runes[i+1] >= 'a' && runes[i+1] <= 'z'
|
||||||
|
|
||||||
|
if prevIsLower || nextIsLower {
|
||||||
|
result.WriteRune('_')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
result.WriteRune(r)
|
result.WriteRune(r)
|
||||||
}
|
}
|
||||||
@@ -961,7 +973,7 @@ func MapToStruct(dataMap map[string]interface{}, target interface{}) error {
|
|||||||
// 4. Field name variations
|
// 4. Field name variations
|
||||||
columnNames = append(columnNames, field.Name)
|
columnNames = append(columnNames, field.Name)
|
||||||
columnNames = append(columnNames, strings.ToLower(field.Name))
|
columnNames = append(columnNames, strings.ToLower(field.Name))
|
||||||
columnNames = append(columnNames, ToSnakeCase(field.Name))
|
// columnNames = append(columnNames, ToSnakeCase(field.Name))
|
||||||
|
|
||||||
// Map all column name variations to this field index
|
// Map all column name variations to this field index
|
||||||
for _, colName := range columnNames {
|
for _, colName := range columnNames {
|
||||||
@@ -1067,7 +1079,7 @@ func setFieldValue(field reflect.Value, value interface{}) error {
|
|||||||
case string:
|
case string:
|
||||||
field.SetBytes([]byte(v))
|
field.SetBytes([]byte(v))
|
||||||
return nil
|
return nil
|
||||||
case map[string]interface{}, []interface{}:
|
case map[string]interface{}, []interface{}, []*any, map[string]*any:
|
||||||
// Marshal complex types to JSON for SqlJSONB fields
|
// Marshal complex types to JSON for SqlJSONB fields
|
||||||
jsonBytes, err := json.Marshal(v)
|
jsonBytes, err := json.Marshal(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1077,6 +1089,11 @@ func setFieldValue(field reflect.Value, value interface{}) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle slice-to-slice conversions (e.g., []interface{} to []*SomeModel)
|
||||||
|
if valueReflect.Kind() == reflect.Slice {
|
||||||
|
return convertSlice(field, valueReflect)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle struct types (like SqlTimeStamp, SqlDate, SqlTime which wrap SqlNull[time.Time])
|
// Handle struct types (like SqlTimeStamp, SqlDate, SqlTime which wrap SqlNull[time.Time])
|
||||||
@@ -1156,6 +1173,92 @@ func setFieldValue(field reflect.Value, value interface{}) error {
|
|||||||
return fmt.Errorf("cannot convert %v to %v", valueReflect.Type(), field.Type())
|
return fmt.Errorf("cannot convert %v to %v", valueReflect.Type(), field.Type())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// convertSlice converts a source slice to a target slice type, handling element-wise conversions
|
||||||
|
// Supports converting []interface{} to slices of structs or pointers to structs
|
||||||
|
func convertSlice(targetSlice reflect.Value, sourceSlice reflect.Value) error {
|
||||||
|
if sourceSlice.Kind() != reflect.Slice || targetSlice.Kind() != reflect.Slice {
|
||||||
|
return fmt.Errorf("both source and target must be slices")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the element type of the target slice
|
||||||
|
targetElemType := targetSlice.Type().Elem()
|
||||||
|
sourceLen := sourceSlice.Len()
|
||||||
|
|
||||||
|
// Create a new slice with the same length as the source
|
||||||
|
newSlice := reflect.MakeSlice(targetSlice.Type(), sourceLen, sourceLen)
|
||||||
|
|
||||||
|
// Convert each element
|
||||||
|
for i := 0; i < sourceLen; i++ {
|
||||||
|
sourceElem := sourceSlice.Index(i)
|
||||||
|
targetElem := newSlice.Index(i)
|
||||||
|
|
||||||
|
// Get the actual value from the source element
|
||||||
|
var sourceValue interface{}
|
||||||
|
if sourceElem.CanInterface() {
|
||||||
|
sourceValue = sourceElem.Interface()
|
||||||
|
} else {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle nil elements
|
||||||
|
if sourceValue == nil {
|
||||||
|
// For pointer types, nil is valid
|
||||||
|
if targetElemType.Kind() == reflect.Ptr {
|
||||||
|
targetElem.Set(reflect.Zero(targetElemType))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// If target element type is a pointer to struct, we need to create new instances
|
||||||
|
if targetElemType.Kind() == reflect.Ptr {
|
||||||
|
// Create a new instance of the pointed-to type
|
||||||
|
newElemPtr := reflect.New(targetElemType.Elem())
|
||||||
|
|
||||||
|
// Convert the source value to the struct
|
||||||
|
switch sv := sourceValue.(type) {
|
||||||
|
case map[string]interface{}:
|
||||||
|
// Source is a map, use MapToStruct to populate the new instance
|
||||||
|
if err := MapToStruct(sv, newElemPtr.Interface()); err != nil {
|
||||||
|
return fmt.Errorf("failed to convert element %d: %w", i, err)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// Try direct conversion or setFieldValue
|
||||||
|
if err := setFieldValue(newElemPtr.Elem(), sourceValue); err != nil {
|
||||||
|
return fmt.Errorf("failed to convert element %d: %w", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElem.Set(newElemPtr)
|
||||||
|
} else if targetElemType.Kind() == reflect.Struct {
|
||||||
|
// Target element is a struct (not a pointer)
|
||||||
|
switch sv := sourceValue.(type) {
|
||||||
|
case map[string]interface{}:
|
||||||
|
// Use MapToStruct to populate the element
|
||||||
|
elemPtr := targetElem.Addr()
|
||||||
|
if elemPtr.CanInterface() {
|
||||||
|
if err := MapToStruct(sv, elemPtr.Interface()); err != nil {
|
||||||
|
return fmt.Errorf("failed to convert element %d: %w", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// Try direct conversion
|
||||||
|
if err := setFieldValue(targetElem, sourceValue); err != nil {
|
||||||
|
return fmt.Errorf("failed to convert element %d: %w", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// For other types, use setFieldValue
|
||||||
|
if err := setFieldValue(targetElem, sourceValue); err != nil {
|
||||||
|
return fmt.Errorf("failed to convert element %d: %w", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the converted slice to the target field
|
||||||
|
targetSlice.Set(newSlice)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// convertToInt64 attempts to convert various types to int64
|
// convertToInt64 attempts to convert various types to int64
|
||||||
func convertToInt64(value interface{}) (int64, bool) {
|
func convertToInt64(value interface{}) (int64, bool) {
|
||||||
switch v := value.(type) {
|
switch v := value.(type) {
|
||||||
|
|||||||
@@ -1453,30 +1453,7 @@ func isNullable(field reflect.StructField) bool {
|
|||||||
|
|
||||||
// GetRelationshipInfo implements common.RelationshipInfoProvider interface
|
// GetRelationshipInfo implements common.RelationshipInfoProvider interface
|
||||||
func (h *Handler) GetRelationshipInfo(modelType reflect.Type, relationName string) *common.RelationshipInfo {
|
func (h *Handler) GetRelationshipInfo(modelType reflect.Type, relationName string) *common.RelationshipInfo {
|
||||||
info := h.getRelationshipInfo(modelType, relationName)
|
return common.GetRelationshipInfo(modelType, relationName)
|
||||||
if info == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Convert internal type to common type
|
|
||||||
return &common.RelationshipInfo{
|
|
||||||
FieldName: info.fieldName,
|
|
||||||
JSONName: info.jsonName,
|
|
||||||
RelationType: info.relationType,
|
|
||||||
ForeignKey: info.foreignKey,
|
|
||||||
References: info.references,
|
|
||||||
JoinTable: info.joinTable,
|
|
||||||
RelatedModel: info.relatedModel,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type relationshipInfo struct {
|
|
||||||
fieldName string
|
|
||||||
jsonName string
|
|
||||||
relationType string // "belongsTo", "hasMany", "hasOne", "many2many"
|
|
||||||
foreignKey string
|
|
||||||
references string
|
|
||||||
joinTable string
|
|
||||||
relatedModel interface{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) applyPreloads(model interface{}, query common.SelectQuery, preloads []common.PreloadOption) (common.SelectQuery, error) {
|
func (h *Handler) applyPreloads(model interface{}, query common.SelectQuery, preloads []common.PreloadOption) (common.SelectQuery, error) {
|
||||||
@@ -1496,7 +1473,7 @@ func (h *Handler) applyPreloads(model interface{}, query common.SelectQuery, pre
|
|||||||
for idx := range preloads {
|
for idx := range preloads {
|
||||||
preload := preloads[idx]
|
preload := preloads[idx]
|
||||||
logger.Debug("Processing preload for relation: %s", preload.Relation)
|
logger.Debug("Processing preload for relation: %s", preload.Relation)
|
||||||
relInfo := h.getRelationshipInfo(modelType, preload.Relation)
|
relInfo := common.GetRelationshipInfo(modelType, preload.Relation)
|
||||||
if relInfo == nil {
|
if relInfo == nil {
|
||||||
logger.Warn("Relation %s not found in model", preload.Relation)
|
logger.Warn("Relation %s not found in model", preload.Relation)
|
||||||
continue
|
continue
|
||||||
@@ -1504,7 +1481,7 @@ func (h *Handler) applyPreloads(model interface{}, query common.SelectQuery, pre
|
|||||||
|
|
||||||
// Use the field name (capitalized) for ORM preloading
|
// Use the field name (capitalized) for ORM preloading
|
||||||
// ORMs like GORM and Bun expect the struct field name, not the JSON name
|
// ORMs like GORM and Bun expect the struct field name, not the JSON name
|
||||||
relationFieldName := relInfo.fieldName
|
relationFieldName := relInfo.FieldName
|
||||||
|
|
||||||
// Validate and fix WHERE clause to ensure it contains the relation prefix
|
// Validate and fix WHERE clause to ensure it contains the relation prefix
|
||||||
if len(preload.Where) > 0 {
|
if len(preload.Where) > 0 {
|
||||||
@@ -1547,13 +1524,13 @@ func (h *Handler) applyPreloads(model interface{}, query common.SelectQuery, pre
|
|||||||
copy(columns, preload.Columns)
|
copy(columns, preload.Columns)
|
||||||
|
|
||||||
// Add foreign key if not already present
|
// Add foreign key if not already present
|
||||||
if relInfo.foreignKey != "" {
|
if relInfo.ForeignKey != "" {
|
||||||
// Convert struct field name (e.g., DepartmentID) to snake_case (e.g., department_id)
|
// Convert struct field name (e.g., DepartmentID) to snake_case (e.g., department_id)
|
||||||
foreignKeyColumn := toSnakeCase(relInfo.foreignKey)
|
foreignKeyColumn := toSnakeCase(relInfo.ForeignKey)
|
||||||
|
|
||||||
hasForeignKey := false
|
hasForeignKey := false
|
||||||
for _, col := range columns {
|
for _, col := range columns {
|
||||||
if col == foreignKeyColumn || col == relInfo.foreignKey {
|
if col == foreignKeyColumn || col == relInfo.ForeignKey {
|
||||||
hasForeignKey = true
|
hasForeignKey = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -1599,58 +1576,6 @@ func (h *Handler) applyPreloads(model interface{}, query common.SelectQuery, pre
|
|||||||
return query, nil
|
return query, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) getRelationshipInfo(modelType reflect.Type, relationName string) *relationshipInfo {
|
|
||||||
// Ensure we have a struct type
|
|
||||||
if modelType == nil || modelType.Kind() != reflect.Struct {
|
|
||||||
logger.Warn("Cannot get relationship info from non-struct type: %v", modelType)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < modelType.NumField(); i++ {
|
|
||||||
field := modelType.Field(i)
|
|
||||||
jsonTag := field.Tag.Get("json")
|
|
||||||
jsonName := strings.Split(jsonTag, ",")[0]
|
|
||||||
|
|
||||||
if jsonName == relationName {
|
|
||||||
gormTag := field.Tag.Get("gorm")
|
|
||||||
info := &relationshipInfo{
|
|
||||||
fieldName: field.Name,
|
|
||||||
jsonName: jsonName,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse GORM tag to determine relationship type and keys
|
|
||||||
if strings.Contains(gormTag, "foreignKey") {
|
|
||||||
info.foreignKey = h.extractTagValue(gormTag, "foreignKey")
|
|
||||||
info.references = h.extractTagValue(gormTag, "references")
|
|
||||||
|
|
||||||
// Determine if it's belongsTo or hasMany/hasOne
|
|
||||||
if field.Type.Kind() == reflect.Slice {
|
|
||||||
info.relationType = "hasMany"
|
|
||||||
} else if field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Struct {
|
|
||||||
info.relationType = "belongsTo"
|
|
||||||
}
|
|
||||||
} else if strings.Contains(gormTag, "many2many") {
|
|
||||||
info.relationType = "many2many"
|
|
||||||
info.joinTable = h.extractTagValue(gormTag, "many2many")
|
|
||||||
}
|
|
||||||
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) extractTagValue(tag, key string) string {
|
|
||||||
parts := strings.Split(tag, ";")
|
|
||||||
for _, part := range parts {
|
|
||||||
part = strings.TrimSpace(part)
|
|
||||||
if strings.HasPrefix(part, key+":") {
|
|
||||||
return strings.TrimPrefix(part, key+":")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// toSnakeCase converts a PascalCase or camelCase string to snake_case
|
// toSnakeCase converts a PascalCase or camelCase string to snake_case
|
||||||
func toSnakeCase(s string) string {
|
func toSnakeCase(s string) string {
|
||||||
var result strings.Builder
|
var result strings.Builder
|
||||||
|
|||||||
@@ -269,8 +269,6 @@ func TestToSnakeCase(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestExtractTagValue(t *testing.T) {
|
func TestExtractTagValue(t *testing.T) {
|
||||||
handler := NewHandler(nil, nil)
|
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
tag string
|
tag string
|
||||||
@@ -311,9 +309,9 @@ func TestExtractTagValue(t *testing.T) {
|
|||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
result := handler.extractTagValue(tt.tag, tt.key)
|
result := common.ExtractTagValue(tt.tag, tt.key)
|
||||||
if result != tt.expected {
|
if result != tt.expected {
|
||||||
t.Errorf("extractTagValue(%q, %q) = %q, expected %q", tt.tag, tt.key, result, tt.expected)
|
t.Errorf("ExtractTagValue(%q, %q) = %q, expected %q", tt.tag, tt.key, result, tt.expected)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,8 +50,9 @@ func SetupMuxRoutes(muxRouter *mux.Router, handler *Handler, authMiddleware Midd
|
|||||||
openAPIHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
openAPIHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
handler.HandleOpenAPI(respAdapter, reqAdapter)
|
handler.HandleOpenAPI(respAdapter, reqAdapter)
|
||||||
})
|
})
|
||||||
muxRouter.Handle("/openapi", openAPIHandler).Methods("GET", "OPTIONS")
|
muxRouter.Handle("/openapi", openAPIHandler).Methods("GET", "OPTIONS")
|
||||||
@@ -98,7 +99,8 @@ func createMuxHandler(handler *Handler, schema, entity, idParam string) http.Han
|
|||||||
// Set CORS headers
|
// Set CORS headers
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
vars := make(map[string]string)
|
vars := make(map[string]string)
|
||||||
vars["schema"] = schema
|
vars["schema"] = schema
|
||||||
@@ -106,7 +108,7 @@ func createMuxHandler(handler *Handler, schema, entity, idParam string) http.Han
|
|||||||
if idParam != "" {
|
if idParam != "" {
|
||||||
vars["id"] = mux.Vars(r)[idParam]
|
vars["id"] = mux.Vars(r)[idParam]
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, vars)
|
handler.Handle(respAdapter, reqAdapter, vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,7 +119,8 @@ func createMuxGetHandler(handler *Handler, schema, entity, idParam string) http.
|
|||||||
// Set CORS headers
|
// Set CORS headers
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
vars := make(map[string]string)
|
vars := make(map[string]string)
|
||||||
vars["schema"] = schema
|
vars["schema"] = schema
|
||||||
@@ -125,7 +128,7 @@ func createMuxGetHandler(handler *Handler, schema, entity, idParam string) http.
|
|||||||
if idParam != "" {
|
if idParam != "" {
|
||||||
vars["id"] = mux.Vars(r)[idParam]
|
vars["id"] = mux.Vars(r)[idParam]
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, vars)
|
handler.HandleGet(respAdapter, reqAdapter, vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,13 +140,14 @@ func createMuxOptionsHandler(handler *Handler, schema, entity string, allowedMet
|
|||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
corsConfig.AllowedMethods = allowedMethods
|
corsConfig.AllowedMethods = allowedMethods
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
// Return metadata in the OPTIONS response body
|
// Return metadata in the OPTIONS response body
|
||||||
vars := make(map[string]string)
|
vars := make(map[string]string)
|
||||||
vars["schema"] = schema
|
vars["schema"] = schema
|
||||||
vars["entity"] = entity
|
vars["entity"] = entity
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, vars)
|
handler.HandleGet(respAdapter, reqAdapter, vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -222,15 +226,16 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// Add global /openapi route
|
// Add global /openapi route
|
||||||
r.Handle("GET", "/openapi", func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("GET", "/openapi", func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
handler.HandleOpenAPI(respAdapter, reqAdapter)
|
handler.HandleOpenAPI(respAdapter, reqAdapter)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
r.Handle("OPTIONS", "/openapi", func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("OPTIONS", "/openapi", func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -253,12 +258,13 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// POST route without ID
|
// POST route without ID
|
||||||
r.Handle("POST", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("POST", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -266,13 +272,14 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// POST route with ID
|
// POST route with ID
|
||||||
r.Handle("POST", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("POST", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
"id": req.Param("id"),
|
"id": req.Param("id"),
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -280,12 +287,13 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// GET route without ID
|
// GET route without ID
|
||||||
r.Handle("GET", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("GET", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -293,13 +301,14 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// GET route with ID
|
// GET route with ID
|
||||||
r.Handle("GET", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("GET", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
"id": req.Param("id"),
|
"id": req.Param("id"),
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -307,14 +316,15 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// OPTIONS route without ID (returns metadata)
|
// OPTIONS route without ID (returns metadata)
|
||||||
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
optionsCorsConfig := corsConfig
|
optionsCorsConfig := corsConfig
|
||||||
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
||||||
common.SetCORSHeaders(respAdapter, optionsCorsConfig)
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -322,14 +332,15 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// OPTIONS route with ID (returns metadata)
|
// OPTIONS route with ID (returns metadata)
|
||||||
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
optionsCorsConfig := corsConfig
|
optionsCorsConfig := corsConfig
|
||||||
optionsCorsConfig.AllowedMethods = []string{"POST", "OPTIONS"}
|
optionsCorsConfig.AllowedMethods = []string{"POST", "OPTIONS"}
|
||||||
common.SetCORSHeaders(respAdapter, optionsCorsConfig)
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -766,7 +766,7 @@ func (h *Handler) applyPreloadWithRecursion(query common.SelectQuery, preload co
|
|||||||
// Apply ComputedQL fields if any
|
// Apply ComputedQL fields if any
|
||||||
if len(preload.ComputedQL) > 0 {
|
if len(preload.ComputedQL) > 0 {
|
||||||
// Get the base table name from the related model
|
// Get the base table name from the related model
|
||||||
baseTableName := getTableNameFromModel(relatedModel)
|
baseTableName := common.GetTableNameFromModel(relatedModel)
|
||||||
|
|
||||||
// Convert the preload relation path to the appropriate alias format
|
// Convert the preload relation path to the appropriate alias format
|
||||||
// This is ORM-specific. Currently we only support Bun's format.
|
// This is ORM-specific. Currently we only support Bun's format.
|
||||||
@@ -777,7 +777,7 @@ func (h *Handler) applyPreloadWithRecursion(query common.SelectQuery, preload co
|
|||||||
underlyingType := fmt.Sprintf("%T", h.db.GetUnderlyingDB())
|
underlyingType := fmt.Sprintf("%T", h.db.GetUnderlyingDB())
|
||||||
if strings.Contains(underlyingType, "bun.DB") {
|
if strings.Contains(underlyingType, "bun.DB") {
|
||||||
// Use Bun's alias format: lowercase with double underscores
|
// Use Bun's alias format: lowercase with double underscores
|
||||||
preloadAlias = relationPathToBunAlias(preload.Relation)
|
preloadAlias = common.RelationPathToBunAlias(preload.Relation)
|
||||||
}
|
}
|
||||||
// For GORM: GORM doesn't use the same alias format, and this fix
|
// For GORM: GORM doesn't use the same alias format, and this fix
|
||||||
// may not be needed since GORM handles preloads differently
|
// may not be needed since GORM handles preloads differently
|
||||||
@@ -792,7 +792,7 @@ func (h *Handler) applyPreloadWithRecursion(query common.SelectQuery, preload co
|
|||||||
// levels of recursive/nested preloads
|
// levels of recursive/nested preloads
|
||||||
adjustedExpr := colExpr
|
adjustedExpr := colExpr
|
||||||
if baseTableName != "" && preloadAlias != "" {
|
if baseTableName != "" && preloadAlias != "" {
|
||||||
adjustedExpr = replaceTableReferencesInSQL(colExpr, baseTableName, preloadAlias)
|
adjustedExpr = common.ReplaceTableReferencesInSQL(colExpr, baseTableName, preloadAlias)
|
||||||
if adjustedExpr != colExpr {
|
if adjustedExpr != colExpr {
|
||||||
logger.Debug("Adjusted computed column expression for %s: '%s' -> '%s'",
|
logger.Debug("Adjusted computed column expression for %s: '%s' -> '%s'",
|
||||||
colName, colExpr, adjustedExpr)
|
colName, colExpr, adjustedExpr)
|
||||||
@@ -903,73 +903,6 @@ func (h *Handler) applyPreloadWithRecursion(query common.SelectQuery, preload co
|
|||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
|
|
||||||
// relationPathToBunAlias converts a relation path like "MAL.MAL.DEF" to the Bun alias format "mal__mal__def"
|
|
||||||
// Bun generates aliases for nested relations by lowercasing and replacing dots with double underscores
|
|
||||||
func relationPathToBunAlias(relationPath string) string {
|
|
||||||
if relationPath == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
// Convert to lowercase and replace dots with double underscores
|
|
||||||
alias := strings.ToLower(relationPath)
|
|
||||||
alias = strings.ReplaceAll(alias, ".", "__")
|
|
||||||
return alias
|
|
||||||
}
|
|
||||||
|
|
||||||
// replaceTableReferencesInSQL replaces references to a base table name in a SQL expression
|
|
||||||
// with the appropriate alias for the current preload level
|
|
||||||
// For example, if baseTableName is "mastertaskitem" and targetAlias is "mal__mal",
|
|
||||||
// it will replace "mastertaskitem.rid_mastertaskitem" with "mal__mal.rid_mastertaskitem"
|
|
||||||
func replaceTableReferencesInSQL(sqlExpr, baseTableName, targetAlias string) string {
|
|
||||||
if sqlExpr == "" || baseTableName == "" || targetAlias == "" {
|
|
||||||
return sqlExpr
|
|
||||||
}
|
|
||||||
|
|
||||||
// Replace both quoted and unquoted table references
|
|
||||||
// Handle patterns like: tablename.column, "tablename".column, tablename."column", "tablename"."column"
|
|
||||||
|
|
||||||
// Pattern 1: tablename.column (unquoted)
|
|
||||||
result := strings.ReplaceAll(sqlExpr, baseTableName+".", targetAlias+".")
|
|
||||||
|
|
||||||
// Pattern 2: "tablename".column or "tablename"."column" (quoted table name)
|
|
||||||
result = strings.ReplaceAll(result, "\""+baseTableName+"\".", "\""+targetAlias+"\".")
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// getTableNameFromModel extracts the table name from a model
|
|
||||||
// It checks the bun tag first, then falls back to converting the struct name to snake_case
|
|
||||||
func getTableNameFromModel(model interface{}) string {
|
|
||||||
if model == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
modelType := reflect.TypeOf(model)
|
|
||||||
|
|
||||||
// Unwrap pointers
|
|
||||||
for modelType != nil && modelType.Kind() == reflect.Ptr {
|
|
||||||
modelType = modelType.Elem()
|
|
||||||
}
|
|
||||||
|
|
||||||
if modelType == nil || modelType.Kind() != reflect.Struct {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// Look for bun tag on embedded BaseModel
|
|
||||||
for i := 0; i < modelType.NumField(); i++ {
|
|
||||||
field := modelType.Field(i)
|
|
||||||
if field.Anonymous {
|
|
||||||
bunTag := field.Tag.Get("bun")
|
|
||||||
if strings.HasPrefix(bunTag, "table:") {
|
|
||||||
return strings.TrimPrefix(bunTag, "table:")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: convert struct name to lowercase (simple heuristic)
|
|
||||||
// This handles cases like "MasterTaskItem" -> "mastertaskitem"
|
|
||||||
return strings.ToLower(modelType.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) handleCreate(ctx context.Context, w common.ResponseWriter, data interface{}, options ExtendedRequestOptions) {
|
func (h *Handler) handleCreate(ctx context.Context, w common.ResponseWriter, data interface{}, options ExtendedRequestOptions) {
|
||||||
// Capture panics and return error response
|
// Capture panics and return error response
|
||||||
defer func() {
|
defer func() {
|
||||||
@@ -2570,10 +2503,10 @@ func (h *Handler) filterExtendedOptions(validator *common.ColumnValidator, optio
|
|||||||
filteredExpand := expand
|
filteredExpand := expand
|
||||||
|
|
||||||
// Get the relationship info for this expand relation
|
// Get the relationship info for this expand relation
|
||||||
relInfo := h.getRelationshipInfo(modelType, expand.Relation)
|
relInfo := common.GetRelationshipInfo(modelType, expand.Relation)
|
||||||
if relInfo != nil && relInfo.relatedModel != nil {
|
if relInfo != nil && relInfo.RelatedModel != nil {
|
||||||
// Create a validator for the related model
|
// Create a validator for the related model
|
||||||
expandValidator := common.NewColumnValidator(relInfo.relatedModel)
|
expandValidator := common.NewColumnValidator(relInfo.RelatedModel)
|
||||||
// Filter columns using the related model's validator
|
// Filter columns using the related model's validator
|
||||||
filteredExpand.Columns = expandValidator.FilterValidColumns(expand.Columns)
|
filteredExpand.Columns = expandValidator.FilterValidColumns(expand.Columns)
|
||||||
|
|
||||||
@@ -2650,110 +2583,7 @@ func (h *Handler) shouldUseNestedProcessor(data map[string]interface{}, model in
|
|||||||
|
|
||||||
// GetRelationshipInfo implements common.RelationshipInfoProvider interface
|
// GetRelationshipInfo implements common.RelationshipInfoProvider interface
|
||||||
func (h *Handler) GetRelationshipInfo(modelType reflect.Type, relationName string) *common.RelationshipInfo {
|
func (h *Handler) GetRelationshipInfo(modelType reflect.Type, relationName string) *common.RelationshipInfo {
|
||||||
info := h.getRelationshipInfo(modelType, relationName)
|
return common.GetRelationshipInfo(modelType, relationName)
|
||||||
if info == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Convert internal type to common type
|
|
||||||
return &common.RelationshipInfo{
|
|
||||||
FieldName: info.fieldName,
|
|
||||||
JSONName: info.jsonName,
|
|
||||||
RelationType: info.relationType,
|
|
||||||
ForeignKey: info.foreignKey,
|
|
||||||
References: info.references,
|
|
||||||
JoinTable: info.joinTable,
|
|
||||||
RelatedModel: info.relatedModel,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type relationshipInfo struct {
|
|
||||||
fieldName string
|
|
||||||
jsonName string
|
|
||||||
relationType string // "belongsTo", "hasMany", "hasOne", "many2many"
|
|
||||||
foreignKey string
|
|
||||||
references string
|
|
||||||
joinTable string
|
|
||||||
relatedModel interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) getRelationshipInfo(modelType reflect.Type, relationName string) *relationshipInfo {
|
|
||||||
// Ensure we have a struct type
|
|
||||||
if modelType == nil || modelType.Kind() != reflect.Struct {
|
|
||||||
logger.Warn("Cannot get relationship info from non-struct type: %v", modelType)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < modelType.NumField(); i++ {
|
|
||||||
field := modelType.Field(i)
|
|
||||||
jsonTag := field.Tag.Get("json")
|
|
||||||
jsonName := strings.Split(jsonTag, ",")[0]
|
|
||||||
|
|
||||||
if jsonName == relationName {
|
|
||||||
gormTag := field.Tag.Get("gorm")
|
|
||||||
info := &relationshipInfo{
|
|
||||||
fieldName: field.Name,
|
|
||||||
jsonName: jsonName,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse GORM tag to determine relationship type and keys
|
|
||||||
if strings.Contains(gormTag, "foreignKey") {
|
|
||||||
info.foreignKey = h.extractTagValue(gormTag, "foreignKey")
|
|
||||||
info.references = h.extractTagValue(gormTag, "references")
|
|
||||||
|
|
||||||
// Determine if it's belongsTo or hasMany/hasOne
|
|
||||||
if field.Type.Kind() == reflect.Slice {
|
|
||||||
info.relationType = "hasMany"
|
|
||||||
// Get the element type for slice
|
|
||||||
elemType := field.Type.Elem()
|
|
||||||
if elemType.Kind() == reflect.Ptr {
|
|
||||||
elemType = elemType.Elem()
|
|
||||||
}
|
|
||||||
if elemType.Kind() == reflect.Struct {
|
|
||||||
info.relatedModel = reflect.New(elemType).Elem().Interface()
|
|
||||||
}
|
|
||||||
} else if field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Struct {
|
|
||||||
info.relationType = "belongsTo"
|
|
||||||
elemType := field.Type
|
|
||||||
if elemType.Kind() == reflect.Ptr {
|
|
||||||
elemType = elemType.Elem()
|
|
||||||
}
|
|
||||||
if elemType.Kind() == reflect.Struct {
|
|
||||||
info.relatedModel = reflect.New(elemType).Elem().Interface()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if strings.Contains(gormTag, "many2many") {
|
|
||||||
info.relationType = "many2many"
|
|
||||||
info.joinTable = h.extractTagValue(gormTag, "many2many")
|
|
||||||
// Get the element type for many2many (always slice)
|
|
||||||
if field.Type.Kind() == reflect.Slice {
|
|
||||||
elemType := field.Type.Elem()
|
|
||||||
if elemType.Kind() == reflect.Ptr {
|
|
||||||
elemType = elemType.Elem()
|
|
||||||
}
|
|
||||||
if elemType.Kind() == reflect.Struct {
|
|
||||||
info.relatedModel = reflect.New(elemType).Elem().Interface()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Field has no GORM relationship tags, so it's not a relation
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) extractTagValue(tag, key string) string {
|
|
||||||
parts := strings.Split(tag, ";")
|
|
||||||
for _, part := range parts {
|
|
||||||
part = strings.TrimSpace(part)
|
|
||||||
if strings.HasPrefix(part, key+":") {
|
|
||||||
return strings.TrimPrefix(part, key+":")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleOpenAPI generates and returns the OpenAPI specification
|
// HandleOpenAPI generates and returns the OpenAPI specification
|
||||||
|
|||||||
@@ -103,8 +103,9 @@ func SetupMuxRoutes(muxRouter *mux.Router, handler *Handler, authMiddleware Midd
|
|||||||
openAPIHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
openAPIHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
handler.HandleOpenAPI(respAdapter, reqAdapter)
|
handler.HandleOpenAPI(respAdapter, reqAdapter)
|
||||||
})
|
})
|
||||||
muxRouter.Handle("/openapi", openAPIHandler).Methods("GET", "OPTIONS")
|
muxRouter.Handle("/openapi", openAPIHandler).Methods("GET", "OPTIONS")
|
||||||
@@ -161,7 +162,8 @@ func createMuxHandler(handler *Handler, schema, entity, idParam string) http.Han
|
|||||||
// Set CORS headers
|
// Set CORS headers
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
vars := make(map[string]string)
|
vars := make(map[string]string)
|
||||||
vars["schema"] = schema
|
vars["schema"] = schema
|
||||||
@@ -169,7 +171,7 @@ func createMuxHandler(handler *Handler, schema, entity, idParam string) http.Han
|
|||||||
if idParam != "" {
|
if idParam != "" {
|
||||||
vars["id"] = mux.Vars(r)[idParam]
|
vars["id"] = mux.Vars(r)[idParam]
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, vars)
|
handler.Handle(respAdapter, reqAdapter, vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -180,7 +182,8 @@ func createMuxGetHandler(handler *Handler, schema, entity, idParam string) http.
|
|||||||
// Set CORS headers
|
// Set CORS headers
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
vars := make(map[string]string)
|
vars := make(map[string]string)
|
||||||
vars["schema"] = schema
|
vars["schema"] = schema
|
||||||
@@ -188,7 +191,7 @@ func createMuxGetHandler(handler *Handler, schema, entity, idParam string) http.
|
|||||||
if idParam != "" {
|
if idParam != "" {
|
||||||
vars["id"] = mux.Vars(r)[idParam]
|
vars["id"] = mux.Vars(r)[idParam]
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, vars)
|
handler.HandleGet(respAdapter, reqAdapter, vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -200,13 +203,14 @@ func createMuxOptionsHandler(handler *Handler, schema, entity string, allowedMet
|
|||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
corsConfig.AllowedMethods = allowedMethods
|
corsConfig.AllowedMethods = allowedMethods
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewHTTPRequest(r)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
|
||||||
// Return metadata in the OPTIONS response body
|
// Return metadata in the OPTIONS response body
|
||||||
vars := make(map[string]string)
|
vars := make(map[string]string)
|
||||||
vars["schema"] = schema
|
vars["schema"] = schema
|
||||||
vars["entity"] = entity
|
vars["entity"] = entity
|
||||||
reqAdapter := router.NewHTTPRequest(r)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, vars)
|
handler.HandleGet(respAdapter, reqAdapter, vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -285,15 +289,8 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// Add global /openapi route
|
// Add global /openapi route
|
||||||
r.Handle("GET", "/openapi", func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("GET", "/openapi", func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
handler.HandleOpenAPI(respAdapter, reqAdapter)
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
r.Handle("OPTIONS", "/openapi", func(w http.ResponseWriter, req bunrouter.Request) error {
|
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -317,24 +314,26 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// GET and POST for /{schema}/{entity}
|
// GET and POST for /{schema}/{entity}
|
||||||
r.Handle("GET", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("GET", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
r.Handle("POST", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("POST", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -342,65 +341,70 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// GET, POST, PUT, PATCH, DELETE for /{schema}/{entity}/:id
|
// GET, POST, PUT, PATCH, DELETE for /{schema}/{entity}/:id
|
||||||
r.Handle("GET", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("GET", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
"id": req.Param("id"),
|
"id": req.Param("id"),
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
r.Handle("POST", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("POST", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
"id": req.Param("id"),
|
"id": req.Param("id"),
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
r.Handle("PUT", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("PUT", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
"id": req.Param("id"),
|
"id": req.Param("id"),
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
r.Handle("PATCH", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("PATCH", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
"id": req.Param("id"),
|
"id": req.Param("id"),
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
r.Handle("DELETE", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("DELETE", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
"id": req.Param("id"),
|
"id": req.Param("id"),
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -408,12 +412,13 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// Metadata endpoint
|
// Metadata endpoint
|
||||||
r.Handle("GET", metadataPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("GET", metadataPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
common.SetCORSHeaders(respAdapter, corsConfig)
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -421,14 +426,15 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// OPTIONS route without ID (returns metadata)
|
// OPTIONS route without ID (returns metadata)
|
||||||
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
optionsCorsConfig := corsConfig
|
optionsCorsConfig := corsConfig
|
||||||
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
||||||
common.SetCORSHeaders(respAdapter, optionsCorsConfig)
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -436,14 +442,15 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler) {
|
|||||||
// OPTIONS route with ID (returns metadata)
|
// OPTIONS route with ID (returns metadata)
|
||||||
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
optionsCorsConfig := corsConfig
|
optionsCorsConfig := corsConfig
|
||||||
optionsCorsConfig.AllowedMethods = []string{"GET", "PUT", "PATCH", "DELETE", "POST", "OPTIONS"}
|
optionsCorsConfig.AllowedMethods = []string{"GET", "PUT", "PATCH", "DELETE", "POST", "OPTIONS"}
|
||||||
common.SetCORSHeaders(respAdapter, optionsCorsConfig)
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"schema": currentSchema,
|
"schema": currentSchema,
|
||||||
"entity": currentEntity,
|
"entity": currentEntity,
|
||||||
}
|
}
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package restheadspec
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestParseModelName(t *testing.T) {
|
func TestParseModelName(t *testing.T) {
|
||||||
@@ -112,3 +114,88 @@ func TestNewStandardBunRouter(t *testing.T) {
|
|||||||
t.Error("Expected router to be created, got nil")
|
t.Error("Expected router to be created, got nil")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExtractTagValue(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
tag string
|
||||||
|
key string
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "Extract existing key",
|
||||||
|
tag: "json:name;validate:required",
|
||||||
|
key: "json",
|
||||||
|
expected: "name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract key with spaces",
|
||||||
|
tag: "json:name ; validate:required",
|
||||||
|
key: "validate",
|
||||||
|
expected: "required",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract key at end",
|
||||||
|
tag: "json:name;validate:required;db:column_name",
|
||||||
|
key: "db",
|
||||||
|
expected: "column_name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Extract key at beginning",
|
||||||
|
tag: "primary:true;json:id;db:user_id",
|
||||||
|
key: "primary",
|
||||||
|
expected: "true",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Key not found",
|
||||||
|
tag: "json:name;validate:required",
|
||||||
|
key: "db",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Empty tag",
|
||||||
|
tag: "",
|
||||||
|
key: "json",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Single key-value pair",
|
||||||
|
tag: "json:name",
|
||||||
|
key: "json",
|
||||||
|
expected: "name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Key with empty value",
|
||||||
|
tag: "json:;validate:required",
|
||||||
|
key: "json",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Key with complex value",
|
||||||
|
tag: "json:user_name,omitempty;validate:required,min=3",
|
||||||
|
key: "json",
|
||||||
|
expected: "user_name,omitempty",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Multiple semicolons",
|
||||||
|
tag: "json:name;;validate:required",
|
||||||
|
key: "validate",
|
||||||
|
expected: "required",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "BUN Tag",
|
||||||
|
tag: "rel:has-many,join:rid_hub=rid_hub_child",
|
||||||
|
key: "join",
|
||||||
|
expected: "rid_hub=rid_hub_child",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result := common.ExtractTagValue(tt.tag, tt.key)
|
||||||
|
if result != tt.expected {
|
||||||
|
t.Errorf("ExtractTagValue(%q, %q) = %q; want %q", tt.tag, tt.key, result, tt.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user