From 929239cc5b3132ee20dc79716a2611b8f80e1fa8 Mon Sep 17 00:00:00 2001 From: ChronosX88 Date: Thu, 5 Sep 2019 23:12:35 +0400 Subject: [PATCH] feat: Implement basic DiskBackend struct with constructor (for now it isn't implementing Backend interface) --- internal/backends/disk/backend.go | 70 +++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 internal/backends/disk/backend.go diff --git a/internal/backends/disk/backend.go b/internal/backends/disk/backend.go new file mode 100644 index 0000000..aeaf60e --- /dev/null +++ b/internal/backends/disk/backend.go @@ -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} +}