// Copyright 2024 Patial Tech (Ankit Patial). // // This file is part of code.patial.tech/go/appcore, which is MIT licensed. // See http://opensource.org/licenses/MIT package uid import ( "sync" "github.com/sqids/sqids-go" ) type Service interface { SquiOptions() sqids.Options } var ( mu sync.Mutex sqidInst *sqids.Sqids sqidOpts *sqids.Options ) func getSqids(svc Service) (*sqids.Sqids, error) { opts := svc.SquiOptions() mu.Lock() defer mu.Unlock() if sqidInst != nil && sqidOpts != nil && opts.Alphabet == sqidOpts.Alphabet && opts.MinLength == sqidOpts.MinLength { return sqidInst, nil } s, err := sqids.New(opts) if err != nil { return nil, err } sqidInst = s sqidOpts = &opts return s, nil } // Encode a slice of IDs into one unique ID func Encode(svc Service, ids ...uint64) (string, error) { s, err := getSqids(svc) if err != nil { return "", err } return s.Encode(ids) // "86Rf07" } // Decode an ID back to slice of IDs func Decode(svc Service, id string) ([]uint64, error) { s, err := getSqids(svc) if err != nil { return nil, err } return s.Decode(id), nil }