ids-svc-product/internal/idgen/snowflake.go
robinj0726 517f629d76 feat: integrate Snowflake ID generation for product and SKU creation
- 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.
2026-07-10 15:56:42 +08:00

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)
}