-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollections.go
68 lines (55 loc) · 1.65 KB
/
collections.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package minidb
import (
"encoding/json"
"path"
"sync"
)
// base function for creating a new collection
func minicollection(filename string, defaultValue interface{}) *MiniCollections {
db := &MiniCollections{
content: []interface{}{},
mutexes: make(map[int]*sync.Mutex),
BaseMiniDB: BaseMiniDB{
db: filename,
mutex: &sync.Mutex{},
},
}
content, f := ensureInitialDB(db.db, defaultValue, "[]")
err := json.Unmarshal(content, &db.content)
logError(err, "(collections) failed to unmarshall content to struct")
if f {
db.writeToDB()
}
return db
}
// Collections creates a new key with an array / slice value.
func (db *MiniDB) Collections(key string) *MiniCollections {
d := db.getOrCreateMutex("cols_" + key)
d.Lock()
defer d.Unlock()
// if the key exists, get the file's name,
// otherwise, create a new one
filename, ok := db.content.Collections[key]
if !ok {
filename = generateFileName("cols")
}
db.content.Collections[key] = filename
db.writeToDB()
return minicollection(path.Join(db.path, filename), nil)
}
// CollectionsWithDefault creates a new key with an array / slice value. If the key doesn't exist,
// it will write the defaultValue as the first data to the db.
func (db *MiniDB) CollectionsWithDefault(key string, defaultValue interface{}) *MiniCollections {
d := db.getOrCreateMutex("cols_" + key)
d.Lock()
defer d.Unlock()
// if the key exists, get the file's name,
// otherwise, create a new one
filename, ok := db.content.Collections[key]
if !ok {
filename = generateFileName("cols")
}
db.content.Collections[key] = filename
db.writeToDB()
return minicollection(path.Join(db.path, filename), defaultValue)
}