- Refactoring for better understanding

- make readAll perfoming better, removing in every iteration a cast for string
This commit is contained in:
Eder Manoel Cale Costa 2019-09-15 23:51:09 -03:00
parent 45f2624802
commit 1327c26e68
1 changed files with 24 additions and 6 deletions

View File

@ -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