2023-12-16 02:25:49 +00:00
|
|
|
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
|
|
|
)
|
|
|
|
|
2023-12-16 02:25:49 +00:00
|
|
|
// Definitions
|
|
|
|
|
2023-12-16 15:08:07 +00:00
|
|
|
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
|
|
|
|
2024-01-24 16:09:39 +00:00
|
|
|
type Transformer 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
|
|
|
}
|
|
|
|
|
2024-01-24 16:09:39 +00:00
|
|
|
type TransformerConfig struct {
|
|
|
|
Type string `json:"type" toml:"type"`
|
|
|
|
Options any `json:"options" toml:"options"`
|
2023-11-17 16:23:40 +00:00
|
|
|
}
|
|
|
|
|
2024-01-24 16:09:39 +00:00
|
|
|
func (v *TransformerConfig) 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
|
|
|
}
|
|
|
|
|
2024-01-24 16:09:39 +00:00
|
|
|
func (v *TransformerConfig) 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
|
|
|
}
|
|
|
|
|
2023-12-16 02:25:49 +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.
|
|
|
|
|
2024-01-24 16:09:39 +00:00
|
|
|
var Transformers = map[string]Transformer{
|
2023-12-16 03:42:14 +00:00
|
|
|
"replacePath": ReplacePath,
|
|
|
|
"compressResponse": CompressResponse,
|
2023-11-17 16:23:40 +00:00
|
|
|
}
|