pye/pseudo_db.go

69 lines
1.4 KiB
Go
Raw Normal View History

2024-10-11 23:57:57 +03:00
package main
import (
"encoding/json"
2024-10-12 09:55:58 +03:00
"log/slog"
2024-10-11 23:57:57 +03:00
"os"
)
2024-10-12 09:55:58 +03:00
// SQLite seems to hate my Mac.
2024-10-11 23:57:57 +03:00
// And I'd rather deal with something easily tinker-able in PoC stage
// So.................
// JSON.
//
// TODO: Kill this, preferably with fire.
func ReadUsers() []User {
data, err := os.ReadFile("./data.json")
if err != nil {
2024-10-12 09:55:58 +03:00
slog.Error("error reading file", "error", err)
2024-10-11 23:57:57 +03:00
}
var users []User
err = json.Unmarshal(data, &users)
if err != nil {
2024-10-12 09:55:58 +03:00
slog.Error("error unmarshalling data", "error", err)
2024-10-11 23:57:57 +03:00
}
return users
}
func AddUser(user User) {
users := ReadUsers()
users = append(users, user)
2024-10-12 09:55:58 +03:00
// slog.Info("users", "users", users)
2024-10-11 23:57:57 +03:00
data, err := json.Marshal(users)
if err != nil {
2024-10-12 09:55:58 +03:00
slog.Error("error marshalling", "error", err)
return
2024-10-11 23:57:57 +03:00
}
2024-10-12 09:55:58 +03:00
f, err := os.OpenFile("./data.json", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
2024-10-11 23:57:57 +03:00
if err != nil {
2024-10-12 09:55:58 +03:00
slog.Error("error opening/creating file data.json")
return
}
if _, err := f.Write(data); err != nil {
slog.Error("error writing to file data.json", "error", err)
return
2024-10-11 23:57:57 +03:00
}
}
func EmailExists(email string) bool {
users := ReadUsers()
for i := 0; i < len(users); i++ {
2024-10-12 09:55:58 +03:00
if users[i].Email == email {
2024-10-11 23:57:57 +03:00
return true
}
}
return false
}
func UserByEmail(email string) (User, bool) {
users := ReadUsers()
for i := 0; i < len(users); i++ {
2024-10-12 09:55:58 +03:00
if users[i].Email == email {
2024-10-11 23:57:57 +03:00
return users[i], true
}
}
return User{}, false
2024-10-12 09:55:58 +03:00
}