This repository has been archived on 2024-05-11. You can view files and clone it, but cannot push or open issues or pull requests.
Corn-Utility/loaders/db.go
toast fb3e0da610
All checks were successful
Build and push container image / build (push) Successful in 38s
Cursed command but it will do.
2023-10-20 16:18:13 +11:00

69 lines
1.3 KiB
Go

package loaders
import (
"encoding/json"
"os"
)
/*
This is a simple database system that peforms CRUD operations on a JSON file.
It will be a proper database system in the future, but for now it will be a JSON file.
Hope this is understandable for future coders.
*/
type DataLoader interface {
Read(filename string) (interface{}, error)
Write(filename string, data interface{}) error
}
type JSON struct{}
func (l *JSON) Read(filename string) (interface{}, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
bytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
data := make(map[string]interface{})
err = json.Unmarshal(bytes, &data)
if err != nil {
return nil, err
}
return data, nil
}
func (l *JSON) Write(filename string, data interface{}) error {
existingData, err := l.Read(filename)
if err != nil {
return err
}
newData := data.(map[string]interface{})
for k, v := range existingData.(map[string]interface{}) {
if newV, ok := newData[k]; ok {
newData[k] = newV
} else {
newData[k] = v
}
}
bytes, err := json.MarshalIndent(newData, "", " ")
if err != nil {
return err
}
err = os.WriteFile(filename, bytes, 0644)
if err != nil {
return err
}
return nil
}