RoadSign/pkg/sign/transformers/module.go

62 lines
1.3 KiB
Go
Raw Normal View History

package transformers
2023-11-17 16:23:40 +00:00
import (
2023-12-10 03:30:31 +00:00
"github.com/gofiber/fiber/v2"
2023-12-16 15:08:07 +00:00
jsoniter "github.com/json-iterator/go"
2023-11-17 16:23:40 +00:00
)
// Definitions
2023-12-16 15:08:07 +00:00
var json = jsoniter.ConfigCompatibleWithStandardLibrary
2023-11-17 16:23:40 +00:00
type RequestTransformer struct {
2023-12-16 03:42:14 +00:00
ModifyRequest func(options any, ctx *fiber.Ctx) error
ModifyResponse func(options any, ctx *fiber.Ctx) error
2023-11-17 16:23:40 +00:00
}
type RequestTransformerConfig struct {
2023-12-10 03:30:31 +00:00
Type string `json:"type" yaml:"type"`
Options any `json:"options" yaml:"options"`
2023-11-17 16:23:40 +00:00
}
2023-12-16 03:42:14 +00:00
func (v *RequestTransformerConfig) TransformRequest(ctx *fiber.Ctx) error {
2023-11-17 16:23:40 +00:00
for k, f := range Transformers {
if k == v.Type {
if f.ModifyRequest != nil {
2023-12-16 03:42:14 +00:00
return f.ModifyRequest(v.Options, ctx)
2023-11-17 16:23:40 +00:00
}
break
}
}
2023-12-16 03:42:14 +00:00
return nil
2023-11-17 16:23:40 +00:00
}
2023-12-16 03:42:14 +00:00
func (v *RequestTransformerConfig) TransformResponse(ctx *fiber.Ctx) error {
2023-11-17 16:23:40 +00:00
for k, f := range Transformers {
if k == v.Type {
if f.ModifyResponse != nil {
2023-12-16 03:42:14 +00:00
return f.ModifyResponse(v.Options, ctx)
2023-11-17 16:23:40 +00:00
}
break
}
}
2023-12-16 03:42:14 +00:00
return nil
2023-11-17 16:23:40 +00:00
}
// Helpers
func DeserializeOptions[T any](data any) T {
var out T
raw, _ := json.Marshal(data)
_ = json.Unmarshal(raw, &out)
return out
}
// Map of Transformers
// Every transformer need to be mapped here so that they can get work.
2023-11-17 16:23:40 +00:00
var Transformers = map[string]RequestTransformer{
2023-12-16 03:42:14 +00:00
"replacePath": ReplacePath,
"compressResponse": CompressResponse,
2023-11-17 16:23:40 +00:00
}