feat: Implement basic DiskBackend struct with constructor (for now it isn't implementing Backend interface)

This commit is contained in:
ChronosX88 2019-09-05 23:12:35 +04:00
parent e5b4e156e9
commit 929239cc5b
Signed by: ChronosXYZ
GPG Key ID: 085A69A82C8C511A

View File

@ -0,0 +1,70 @@
package disk
import (
"fmt"
"regexp"
"sync"
"github.com/HouzuoGuo/tiedot/db"
)
const (
DatabasePath = "signaller.db" // TODO: make changing the path of database
UsersColName = "users"
RoomsColName = "rooms"
EventsColName = "events"
RoomAliasesColName = "roomAliases"
)
func createCollections(database *db.DB) {
if err := database.Create(UsersColName); err != nil {
panic(err)
}
if err := database.Create(RoomsColName); err != nil {
panic(err)
}
if err := database.Create(EventsColName); err != nil {
panic(err)
}
if err := database.Create(RoomAliasesColName); err != nil {
panic(err)
}
}
func defaultValidationUsernameFunc(userName string) error {
const re = `^\w{5,}$`
if !regexp.MustCompile(re).MatchString(userName) {
return fmt.Errorf("username does not match %s", re)
}
return nil
}
type DiskBackend struct {
currentDatabase *db.DB
users *db.Col
rooms *db.Col
events *db.Col
roomAliases *db.Col
hostname string
validateUsernameFunc func(string) error // TODO: create ability to redefine validation func
mutex sync.RWMutex
}
func NewDiskBackend(hostname string) *DiskBackend {
database, err := db.OpenDB(DatabasePath)
if err != nil {
panic(err)
}
createCollections(database)
return &DiskBackend{
currentDatabase: database,
users: database.Use(UsersColName),
rooms: database.Use(RoomsColName),
events: database.Use(EventsColName),
roomAliases: database.Use(RoomAliasesColName),
hostname: hostname,
validateUsernameFunc: defaultValidationUsernameFunc}
}