diff --git a/scribble.go b/scribble.go index bea590e..7399f9a 100644 --- a/scribble.go +++ b/scribble.go @@ -8,6 +8,7 @@ import ( "io/ioutil" "os" "path/filepath" + "strings" "sync" "github.com/jcelliott/lumber" @@ -149,7 +150,12 @@ func (d *Driver) Read(collection, resource string, v interface{}) error { // record := filepath.Join(d.dir, collection, resource) - // read record from database; if the file doesn't exist `read` will return an err + // check to see if file exists + if _, err := stat(record); err != nil { + return err + } + + // read record from database return read(record, v) } @@ -175,6 +181,14 @@ func (d *Driver) ReadAll(collection string) ([][]byte, error) { // dir := filepath.Join(d.dir, collection) + os.MkdirAll(dir, 0777) + + // read all the files in the transaction.Collection; an error here just means + // the collection is either empty or doesn't exist + files, err := ioutil.ReadDir(dir) + if err != nil { + return nil, err + } // read all the files in the transaction.Collection; an error here just means // the collection is either empty or doesn't exist @@ -208,7 +222,41 @@ func readAll(files []os.FileInfo, dir string) ([][]byte, error) { return records, nil } -// Delete locks the database then attempts to remove the collection/resource +// List ID of records from a collection; this is returned as a slice of strings. +func (d *Driver) List(collection string) ([]string, error) { + + // ensure there is a collection to read + if collection == "" { + return nil, ErrMissingCollection + } + + // + dir := filepath.Join(d.dir, collection) + + // check to see if collection (directory) exists + //if _, err := stat(dir); err != nil { + // return nil, err + //} + + files, err := ioutil.ReadDir(dir) + if err != nil { + return nil, err + } + + // the IDs of collection + var recordsIDs []string + + for _, file := range files { + name := file.Name() + if strings.HasSuffix(name, ".json") && !strings.HasPrefix(name, ".#") { + recordsIDs = append(recordsIDs, name[:len(name)-5]) + } + } + + return recordsIDs, nil +} + +// Delete locks that database and then attempts to remove the collection/resource // specified by [path] func (d *Driver) Delete(collection, resource string) error { path := filepath.Join(collection, resource)