From ee1a597c9e95a54666c7196d121e2e935fe0a6c6 Mon Sep 17 00:00:00 2001 From: Gabriel De Los Rios Date: Sun, 6 Apr 2025 21:54:26 -0300 Subject: [PATCH] feat(cache): implement cache for cuit info --- cache/cache.go | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 cache/cache.go diff --git a/cache/cache.go b/cache/cache.go new file mode 100644 index 0000000..5889a1a --- /dev/null +++ b/cache/cache.go @@ -0,0 +1,41 @@ +package cache + +import ( + "errors" + "fmt" + "os" + "time" + + "github.com/gabdlr/api-cuit-go/utils" +) + +const cacheDir = "./.cache" + +func cacheIsOld(fPath string) bool { + fInfo, _ := os.Stat(fPath) + fCreationDate := fInfo.ModTime() + oneYearAgo := (time.Now()).AddDate(-1, 0, 0) + isOld := fCreationDate.Before(oneYearAgo) + if isOld { + os.Remove(fPath) + } + return isOld +} + +func Search(cuit string) ([]byte, error) { + cuit = utils.StandardizeCuit(cuit) + fPath := fmt.Sprintf("%s/%s.json", cacheDir, cuit) + f, err := os.ReadFile(fPath) + if err == nil { + if cacheIsOld(fPath) { + return []byte{0}, errors.New("cached file expired") + } + return f, nil + } + return []byte{0}, err +} + +func Save(cuit string, cuitInfo []byte) { + cuit = utils.StandardizeCuit(cuit) + os.WriteFile(fmt.Sprintf("%s/%s.json", cacheDir, cuit), cuitInfo, 0644) +}