Extract id generation to own file

This commit is contained in:
Peter Stuifzand 2021-01-17 14:22:45 +01:00
parent f7b1935ce3
commit 7a72931527
2 changed files with 42 additions and 32 deletions

32
file.go
View File

@ -40,38 +40,6 @@ type Block struct {
Parent string Parent string
} }
type ID struct {
StrID string
WasInt bool
}
func (id *ID) UnmarshalJSON(data []byte) error {
var intID int
err := json.Unmarshal(data, &intID)
if err == nil {
*id = ID{strconv.FormatInt(int64(intID), 10), true}
return nil
}
var strID string
err = json.Unmarshal(data, &strID)
if err == nil {
*id = ID{strID, false}
return nil
}
return fmt.Errorf("could not unmarshal %q as an int or string", data)
}
func (id *ID) NewID() string {
if id.WasInt {
l := time.Now().UnixNano()
r := rand.Uint64()
return fmt.Sprintf("_%d_%d", l, r)
} else {
return id.StrID
}
}
// ListItemV2 is way to convert from old structure to new structure // ListItemV2 is way to convert from old structure to new structure
type ListItemV2 struct { type ListItemV2 struct {

42
id.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"encoding/json"
"fmt"
"math/rand"
"strconv"
"time"
)
type ID struct {
StrID string
WasInt bool
}
func (id *ID) UnmarshalJSON(data []byte) error {
var intID int
err := json.Unmarshal(data, &intID)
if err == nil {
*id = ID{strconv.FormatInt(int64(intID), 10), true}
return nil
}
var strID string
err = json.Unmarshal(data, &strID)
if err == nil {
*id = ID{strID, false}
return nil
}
return fmt.Errorf("could not unmarshal %q as an int or string", data)
}
func (id *ID) NewID() string {
if id.WasInt {
l := time.Now().UnixNano()
r := rand.Uint64()
return fmt.Sprintf("_%d_%d", l, r)
} else {
return id.StrID
}
}