-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeys.go
54 lines (45 loc) · 1.06 KB
/
keys.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
51
52
53
54
package minidb
import (
"encoding/json"
"path"
"sync"
)
// this is helper for creating a new key db
func minidb(dir, filename string) *MiniDB {
db := &MiniDB{
path: dir,
filename: filename,
content: MiniDBContent{
Keys: map[string]string{},
Collections: map[string]string{},
Store: map[string]string{},
},
mutexes: make(map[string]*sync.Mutex),
BaseMiniDB: BaseMiniDB{
db: path.Join(dir, filename),
mutex: &sync.Mutex{},
},
}
if content, f := ensureInitialDB(db.db, nil, "{}"); f {
db.writeToDB()
} else {
json.Unmarshal(content, &db.content)
}
return db
}
// Key creates a new key in the json.
// It is better to use this for nesting and only if needed.
func (db *MiniDB) Key(key string) *MiniDB {
d := db.getOrCreateMutex("keys_" + key)
d.Lock()
defer d.Unlock()
// if the key exists, get the file's name,
// otherwise, create a new one
filename, ok := db.content.Keys[key]
if !ok {
filename = generateFileName("key")
}
db.content.Keys[key] = filename
db.writeToDB()
return minidb(db.path, filename)
}