refactor db accessor

This commit is contained in:
2024-08-26 13:10:34 -05:00
parent 3bf2b4d71f
commit e6947e714d
19 changed files with 516 additions and 302 deletions

100
core/nkode/in_memory_db.go Normal file
View File

@@ -0,0 +1,100 @@
package nkode
import (
"errors"
"fmt"
m "go-nkode/core/model"
)
type InMemoryDb struct {
Customers map[m.CustomerId]Customer
Users map[m.UserId]User
userIdMap map[string]m.UserId
}
func NewInMemoryDb() InMemoryDb {
return InMemoryDb{
Customers: make(map[m.CustomerId]Customer),
Users: make(map[m.UserId]User),
userIdMap: make(map[string]m.UserId),
}
}
func (db *InMemoryDb) GetCustomer(id m.CustomerId) (*Customer, error) {
customer, exists := db.Customers[id]
if !exists {
return nil, errors.New(fmt.Sprintf("customer %s dne", customer.Id))
}
return &customer, nil
}
func (db *InMemoryDb) GetUser(username m.Username, customerId m.CustomerId) (*User, error) {
key := userIdKey(customerId, username)
userId, exists := db.userIdMap[key]
if !exists {
return nil, errors.New(fmt.Sprintf("customer %s with username %s dne", customerId, username))
}
user, exists := db.Users[userId]
if !exists {
panic(fmt.Sprintf("userId %s with customerId %s and username %s with no user", userId, customerId, username))
}
return &user, nil
}
func (db *InMemoryDb) WriteNewCustomer(customer Customer) error {
_, exists := db.Customers[customer.Id]
if exists {
return errors.New(fmt.Sprintf("can write customer %s; already exists", customer.Id))
}
db.Customers[customer.Id] = customer
return nil
}
func (db *InMemoryDb) WriteNewUser(user User) error {
_, exists := db.Customers[user.CustomerId]
if !exists {
return errors.New(fmt.Sprintf("can't add user %s to customer %s: customer dne", user.Username, user.CustomerId))
}
userExists, _ := db.GetUser(user.Username, user.CustomerId)
if userExists != nil {
return errors.New(fmt.Sprintf("can't write new user %s, alread exists", user.Username))
}
key := userIdKey(user.CustomerId, user.Username)
db.userIdMap[key] = user.Id
db.Users[user.Id] = user
return nil
}
func (db *InMemoryDb) UpdateUserInterface(userId m.UserId, ui UserInterface) error {
user, exists := db.Users[userId]
if !exists {
return errors.New(fmt.Sprintf("can't update user %s, dne", user.Id))
}
user.Interface = ui
return nil
}
func (db *InMemoryDb) Renew(id m.CustomerId) error {
customer, exists := db.Customers[id]
if !exists {
return errors.New(fmt.Sprintf("customer %s does not exist", id))
}
setXor, attrsXor := customer.RenewKeys()
var err error
for _, user := range db.Users {
if user.CustomerId == id {
err = user.RenewKeys(setXor[:user.Kp.AttrsPerKey], attrsXor[:user.Kp.TotalAttrs()])
if err != nil {
panic(err)
}
}
}
return nil
}
func userIdKey(customerId m.CustomerId, username m.Username) string {
key := fmt.Sprintf("%s:%s", customerId, username)
return key
}