Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 29 additions & 19 deletions wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,43 @@ import (
"runtime"
"strconv"
"strings"
"sync"
)

var (
storefrontCache map[int]string
storefrontCacheOnce sync.Once
)

func parseStorefrontID(id string) string {
sfID, err := strconv.Atoi(strings.Split(id, "-")[0])
if err != nil {
panic(err)
}
type StorefrontMapping struct {
Name string `json:"name"`
Code string `json:"code"`
StorefrontId int `json:"storefrontId"`
}
var mapping []StorefrontMapping
file, err := os.ReadFile("data/storefront_ids.json")
if err != nil {
panic(err)
}
err = json.Unmarshal(file, &mapping)
if err != nil {
panic(err)
}
for _, element := range mapping {
if element.StorefrontId == sfID {
return element.Code

storefrontCacheOnce.Do(func() {
type StorefrontMapping struct {
Name string `json:"name"`
Code string `json:"code"`
StorefrontId int `json:"storefrontId"`
}
}
return ""
var mapping []StorefrontMapping
file, err := os.ReadFile("data/storefront_ids.json")
if err != nil {
panic(err)
}
err = json.Unmarshal(file, &mapping)
if err != nil {
panic(err)
}

storefrontCache = make(map[int]string)
for _, element := range mapping {
storefrontCache[element.StorefrontId] = element.Code
}
})

return storefrontCache[sfID]
}

func PrepareWrapper(mirror bool) {
Expand Down
51 changes: 51 additions & 0 deletions wrapper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package main

import (
"os"
"testing"
)

func setupStorefrontFile() (func(), error) {
const filename = "data/storefront_ids.json"
originalContent, err := os.ReadFile(filename)
originalExists := err == nil

content := `[{"name":"United States","code":"us","storefrontId":143441},{"name":"China","code":"cn","storefrontId":143465}]`
_ = os.MkdirAll("data", 0755)
_ = os.WriteFile(filename, []byte(content), 0644)

teardown := func() {
os.Remove(filename)
if originalExists {
os.WriteFile(filename, originalContent, 0644)
}
}
return teardown, nil
}

func TestParseStorefrontID(t *testing.T) {
teardown, _ := setupStorefrontFile()
defer teardown()

// Verify known ID
code := parseStorefrontID("143441-1,29")
if code != "us" {
t.Errorf("Expected 'us', got '%s'", code)
}

// Verify another known ID
code = parseStorefrontID("143465-something")
if code != "cn" {
t.Errorf("Expected 'cn', got '%s'", code)
}
}

func BenchmarkParseStorefrontID(b *testing.B) {
teardown, _ := setupStorefrontFile()
defer teardown()

b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = parseStorefrontID("143441-1,29")
}
}