mirror of
https://github.com/hanzoai/commerce.git
synced 2026-10-30 15:08:42 +00:00
Multi-tenant commerce and billing: orders, subscriptions, invoices, plans, usage metering and a credit ledger. One Go binary. MIT OR Apache-2.0. Claude-Session: https://claude.ai/code/session_01SAtaDFm8VDiWrhYHNNtxMw
60 lines
961 B
Go
60 lines
961 B
Go
package hashid
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/speps/go-hashids"
|
|
|
|
"github.com/hanzoai/commerce/config"
|
|
)
|
|
|
|
var hd = hashids.NewData()
|
|
|
|
var MalformedHashId = errors.New("Hash id is malformed")
|
|
|
|
func init() {
|
|
hd.Salt = config.Secret
|
|
hd.MinLength = 10
|
|
}
|
|
|
|
func Encode(numbers ...int) string {
|
|
h, err := hashids.NewWithData(hd)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
hashid, err := h.Encode(numbers)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return hashid
|
|
}
|
|
|
|
func Decode(hashid string) ([]int, error) {
|
|
h, err := hashids.NewWithData(hd)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return h.DecodeWithError(hashid)
|
|
}
|
|
|
|
func GetNamespace(ctx context.Context, hashid string) (string, error) {
|
|
ids, err := Decode(hashid)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// ids should never be empty...
|
|
idsLen := len(ids)
|
|
if idsLen <= 0 {
|
|
return "", MalformedHashId
|
|
}
|
|
|
|
id := ids[idsLen-1]
|
|
ns, err := decodeNamespace(ctx, id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return ns, nil
|
|
}
|