/
file.go
50 lines (40 loc) · 1.42 KB
/
file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package sus
import(
`os`
`io/ioutil`
)
// Creates and configures a store that stores entities by converting them to and from json []byte data and keeps them in the local file system.
func NewJsonFileStore(storeDir string, idf IdFactory, vf VersionFactory, ei EntityInitializer) (Store, error) {
return NewFileStore(storeDir, `json`, jsonMarshaler, jsonUnmarshaler, idf, vf, ei)
}
// Creates and configures a store that stores entities by converting them to and from []byte and keeps them in the local file system.
func NewFileStore(storeDir string, fileExt string, m Marshaler, un Unmarshaler, idf IdFactory, vf VersionFactory, ei EntityInitializer) (Store, error) {
err := os.MkdirAll(storeDir, os.ModeDir)
if err != nil {
return nil, err
}
getFileName := func(id string) string {
return storeDir + `/` + id + `.` + fileExt
}
get := func(id string) ([]byte, error) {
fn := getFileName(id)
if _, err := os.Stat(fn); err != nil {
if os.IsNotExist(err) {
err = localEntityDoesNotExistError{id}
}
return nil, err
}
return ioutil.ReadFile(fn)
}
put := func(id string, d []byte) error {
return ioutil.WriteFile(getFileName(id), d, os.ModeAppend)
}
del := func(id string) error {
return os.Remove(getFileName(id))
}
isNonExtantError := func(err error) bool {
_, ok := err.(localEntityDoesNotExistError)
return ok
}
return NewMutexByteStore(get, put, del, m, un, idf, vf, ei, isNonExtantError), nil
}