jsondb: add List method
And add some additional tests.
This commit is contained in:
parent
d74a63f4f2
commit
2b7adb3200
2 changed files with 60 additions and 23 deletions
|
|
@ -22,6 +22,7 @@ import (
|
|||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type JSONDatabase struct {
|
||||
|
|
@ -55,6 +56,27 @@ func (db *JSONDatabase) Read(name string, document interface{}) (bool, error) {
|
|||
return true, nil
|
||||
}
|
||||
|
||||
// Returns a list of all documents' names.
|
||||
func (db *JSONDatabase) List() ([]string, error) {
|
||||
f, err := os.Open(db.dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
infos, err := f.Readdir(-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
names := make([]string, len(infos))
|
||||
for i, info := range infos {
|
||||
names[i] = strings.TrimSuffix(info.Name(), ".json")
|
||||
}
|
||||
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// Writes `document` to `name`, overwriting a previous document if it exists.
|
||||
// `document` must be serializable to JSON.
|
||||
func (db *JSONDatabase) Write(name string, document interface{}) error {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue