69 lines
1014 B
Go
69 lines
1014 B
Go
package db
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"sync"
|
|
)
|
|
|
|
type Database struct {
|
|
Users map[string][]map[string]any `json:"Users"`
|
|
}
|
|
|
|
type UserIdType string
|
|
|
|
const (
|
|
UserId UserIdType = "userId"
|
|
Bid UserIdType = "bid"
|
|
)
|
|
|
|
var (
|
|
DB Database
|
|
mu sync.Mutex
|
|
path = "db.json"
|
|
)
|
|
|
|
func Init(servers []string) {
|
|
data, err := os.ReadFile(path)
|
|
if err == nil {
|
|
json.Unmarshal(data, &DB)
|
|
}
|
|
|
|
if DB.Users == nil {
|
|
DB.Users = make(map[string][]map[string]any)
|
|
}
|
|
|
|
for _, s := range servers {
|
|
if DB.Users[s] == nil {
|
|
DB.Users[s] = []map[string]any{}
|
|
}
|
|
}
|
|
|
|
Save()
|
|
}
|
|
|
|
func Save() {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
data, _ := json.MarshalIndent(DB, "", " ")
|
|
|
|
tmp := path + ".tmp"
|
|
os.WriteFile(tmp, data, 0644)
|
|
os.Rename(tmp, path)
|
|
}
|
|
|
|
func FindUser(id string, idType ...UserIdType) map[string]any {
|
|
key := UserId
|
|
if len(idType) > 0 {
|
|
key = idType[0]
|
|
}
|
|
for _, user := range DB.Users[os.Getenv("SERVER")] {
|
|
if fmt.Sprintf("%v", user[string(key)]) == id {
|
|
return user
|
|
}
|
|
}
|
|
return nil
|
|
}
|