mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
- Added a new ID generator using the Snowflake algorithm to create unique identifiers for products and SKUs. - Updated the product server to utilize the ID generator for assigning IDs during product and SKU creation. - Refactored the product repository to accommodate the new ID handling logic. - Introduced unit tests for the ID generator to ensure correct functionality and error handling.
42 lines
960 B
Go
42 lines
960 B
Go
package idgen
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
|
|
"github.com/bwmarrin/snowflake"
|
|
)
|
|
|
|
// Generator creates 64-bit, time-sortable Snowflake IDs.
|
|
type Generator struct {
|
|
node *snowflake.Node
|
|
}
|
|
|
|
// NewFromEnv creates a generator using SNOWFLAKE_WORKER_ID, defaulting to 1.
|
|
func NewFromEnv() (*Generator, error) {
|
|
workerID := int64(1)
|
|
if raw := os.Getenv("SNOWFLAKE_WORKER_ID"); raw != "" {
|
|
parsed, err := strconv.ParseInt(raw, 10, 64)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse SNOWFLAKE_WORKER_ID: %w", err)
|
|
}
|
|
workerID = parsed
|
|
}
|
|
node, err := snowflake.NewNode(workerID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create snowflake node: %w", err)
|
|
}
|
|
return &Generator{node: node}, nil
|
|
}
|
|
|
|
// Next returns a new Snowflake ID.
|
|
func (g *Generator) Next() int64 {
|
|
return g.node.Generate().Int64()
|
|
}
|
|
|
|
// NextString returns a decimal string representation of Next.
|
|
func (g *Generator) NextString() string {
|
|
return strconv.FormatInt(g.Next(), 10)
|
|
}
|