redis/js_export.go

68 lines
1.5 KiB
Go
Raw Normal View History

package redis
import (
"context"
"errors"
"apigo.cc/go/id"
"apigo.cc/go/jsmod"
)
func init() {
jsmod.Register("redis", map[string]any{
"get": func(ctx context.Context, name string) (*jsRedis, error) {
rd := GetRedis(name, nil)
if rd.Error != nil {
return nil, rd.Error
}
return &jsRedis{rd: rd, ctx: ctx}, nil
},
})
}
type jsRedis struct {
rd *Redis
ctx context.Context
idMaker *id.IDMaker
}
var errSafeMode = errors.New("redis operation is restricted in safe mode")
func (jr *jsRedis) checkSafe() error {
if jsmod.IsSafeMode(jr.ctx) {
return errSafeMode
}
return nil
}
// Do executes any redis command. In SafeMode, it only allows read-only commands.
// Note: Since we don't have a reliable way to categorize all redis commands as read-only,
// and 'DO' is used for everything, we strictly block 'DO' in SafeMode if it's not a known read-only command.
// For simplicity and maximum safety as requested, we block 'DO' entirely in SafeMode.
func (jr *jsRedis) Do(cmd string, args ...any) *Result {
if jr.checkSafe() != nil {
return &Result{Error: errSafeMode}
}
return jr.rd.Do(cmd, args...)
}
// ID Generation Helpers
func (jr *jsRedis) getIDMaker() *id.IDMaker {
if jr.idMaker == nil {
jr.idMaker = NewIDMaker(jr.rd)
}
return jr.idMaker
}
func (jr *jsRedis) GetID(size int) string {
return jr.getIDMaker().Get(size)
}
func (jr *jsRedis) GetForMysql(size int) string {
return jr.getIDMaker().GetForMysql(size)
}
func (jr *jsRedis) GetForPostgreSQL(size int) string {
return jr.getIDMaker().GetForPostgreSQL(size)
}