From 6d5b9d880ba86e685ab44cd4eacbd990e3f0f123 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Mon, 22 May 2023 17:14:32 -0400 Subject: [PATCH] refactor: deduplicate building api urls --- service/files/files.go | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/service/files/files.go b/service/files/files.go index 100b33a..b74898c 100644 --- a/service/files/files.go +++ b/service/files/files.go @@ -65,7 +65,7 @@ func Upload(r io.ReadSeeker, size int64, hash []byte) (model.Upload, error) { } } - objectExistsResult, err := client.R().Get(fmt.Sprintf("/worker/objects/%s", hashHex)) + objectExistsResult, err := client.R().Get(getBusObjectUrl(hashHex)) if err != nil { shared.GetLogger().Error("Failed query object", zap.Error(err)) @@ -84,7 +84,7 @@ func Upload(r io.ReadSeeker, size int64, hash []byte) (model.Upload, error) { objectStatusCode = 404 } - proofExistsResult, err := client.R().Get(fmt.Sprintf("/worker/objects/%s.obao", hashHex)) + proofExistsResult, err := client.R().Get(getBusProofUrl(hashHex)) if err != nil { shared.GetLogger().Error("Failed query object proof", zap.Error(err)) @@ -109,14 +109,14 @@ func Upload(r io.ReadSeeker, size int64, hash []byte) (model.Upload, error) { return upload, errors.New(msg) } - ret, err := client.R().SetBody(r).Put(fmt.Sprintf("/worker/objects/%s", hashHex)) + ret, err := client.R().SetBody(r).Put(getWorkerObjectUrl(hashHex)) if ret.StatusCode() != 200 { shared.GetLogger().Error("Failed uploading object", zap.String("error", ret.String())) err = errors.New(ret.String()) return upload, err } - ret, err = client.R().SetBody(tree).Put(fmt.Sprintf("/worker/objects/%s.obao", hashHex)) + ret, err = client.R().SetBody(tree).Put(getWorkerProofUrl(hashHex)) if ret.StatusCode() != 200 { shared.GetLogger().Error("Failed uploading proof", zap.String("error", ret.String())) err = errors.New(ret.String()) @@ -172,3 +172,37 @@ func Download(hash string) (io.Reader, error) { return nil, errors.New("invalid file") } } + +func objectUrlBuilder(hash string, bus bool, proof bool) string { + path := []string{} + if bus { + path = append(path, "bus") + } else { + path = append(path, "worker") + } + + path = append(path, "objects") + + name := "%s" + + if proof { + name = name + ".obao" + } + + path = append(path, name) + + return fmt.Sprintf(strings.Join(path, "/"), hash) +} + +func getBusObjectUrl(hash string) string { + return objectUrlBuilder(hash, true, false) +} +func getWorkerObjectUrl(hash string) string { + return objectUrlBuilder(hash, false, false) +} +func getWorkerProofUrl(hash string) string { + return objectUrlBuilder(hash, false, true) +} +func getBusProofUrl(hash string) string { + return objectUrlBuilder(hash, true, true) +}