From 1327c26e681f2a904009d4f89ca95bc5a3471453 Mon Sep 17 00:00:00 2001 From: Eder Manoel Cale Costa Date: Sun, 15 Sep 2019 23:51:09 -0300 Subject: [PATCH] - Refactoring for better understanding - make readAll perfoming better, removing in every iteration a cast for string --- scribble.go | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/scribble.go b/scribble.go index e271727..1f6ece0 100644 --- a/scribble.go +++ b/scribble.go @@ -108,12 +108,17 @@ func (d *Driver) Write(collection, resource string, v interface{}) error { fnlPath := filepath.Join(dir, resource+".json") tmpPath := fnlPath + ".tmp" + return write(dir, tmpPath, fnlPath, v) +} + +func write(dir, tmpPath, dstPath string, v interface{}) error { + // create collection directory if err := os.MkdirAll(dir, 0755); err != nil { return err } - // + // marshal the pointer to a non-struct and indent with tab b, err := json.MarshalIndent(v, "", "\t") if err != nil { return err @@ -125,7 +130,7 @@ func (d *Driver) Write(collection, resource string, v interface{}) error { } // move final file into place - return os.Rename(tmpPath, fnlPath) + return os.Rename(tmpPath, dstPath) } // Read a record from the database @@ -150,7 +155,13 @@ func (d *Driver) Read(collection, resource string, v interface{}) error { } // read record from database + return read(record, v) +} + +func read(record string, v interface{}) error { + b, err := ioutil.ReadFile(record + ".json") + if err != nil { return err } @@ -161,7 +172,7 @@ func (d *Driver) Read(collection, resource string, v interface{}) error { // ReadAll records from a collection; this is returned as a slice of strings because // there is no way of knowing what type the record is. -func (d *Driver) ReadAll(collection string) ([]string, error) { +func (d *Driver) ReadAll(collection string) ([][]byte, error) { // ensure there is a collection to read if collection == "" { @@ -180,19 +191,26 @@ func (d *Driver) ReadAll(collection string) ([]string, error) { // the collection is either empty or doesn't exist files, _ := ioutil.ReadDir(dir) + return readAll(files, dir) +} + +func readAll(files []os.FileInfo, dir string) ([][]byte, error) { // the files read from the database - var records []string + var records [][]byte // iterate over each of the files, attempting to read the file. If successful - // append the files to the collection of read files + // append the files to the collection of read for _, file := range files { + b, err := ioutil.ReadFile(filepath.Join(dir, file.Name())) + if err != nil { return nil, err } // append read file - records = append(records, string(b)) + // No need to cast to string in every iteration + records = append(records, b) } // unmarhsal the read files as a comma delimeted byte array