diff --git a/mongodb/adapter.go b/mongodb/adapter.go index b248365..76033e2 100644 --- a/mongodb/adapter.go +++ b/mongodb/adapter.go @@ -9,6 +9,10 @@ import ( "time" ) +const errNoCollection string = "collection not found: felt.%s" +const errNoDocument string = "document with name/id '%s' doesn't exist in collection: %s" +const errNotAString string = "document property is not a string: %s.%s" + type DbAdapter interface { Init(mongoUri string) error @@ -82,14 +86,59 @@ func (self *DbEngine) ensureCollections(db mongo.Database) error { func (self *DbEngine) CreateTable(table models.TableKey) error { tables := self.db.Collection("tables") if tables != nil { - _, err := tables.insertOne(self.mkCtx(10), bson.D{ + _, err := tables.InsertOne(self.mkCtx(10), bson.D{ {"name", table.Name}, {"passcode", table.Passcode}, {"mapUri", ""}, {"diceRolls", bson.A{}}, {"tokens", bson.A{}}, }) + return err + } + return errors.New(fmt.Sprintf(errNoCollection, "tables")) + +} + +func (self *DbEngine) SetMapImageUrl(table models.TableKey, url string) error { + tables := self.db.Collection("tables") + if tables != nil { + _, err := tables.UpdateOne( + self.mkCtx(10), + bson.D{ + {"name", table.Name}, + {"passcode", table.Passcode}, + }, + bson.D{ + {"mapImageUrl", url}, + }, + ) + + return err } - return err + return errors.New(fmt.Sprintf(errNoCollection, "tables")) +} + +func (self *DbEngine) GetMapImageUrl(table models.TableKey) (string, error) { + tables := self.db.Collection("tables") + if tables != nil { + fromDb := tables.FindOne( + self.mkCtx(10), + bson.D{ + {"name", table.Name}, + {"passcode", table.Passcode}, + }) + if fromDb != nil { + url, ok := fromDb.Lookup("mapUri").StringValueOK() + if ok { + return url, nil + } else { + return "", errors.New(fmt.Sprintf(errNotAString, "table", table.Name, "mapUri")) + } + } else { + return "", errors.New(fmt.Sprintf(errNoDocument, table.Name, "tables")) + } + } + + return "", errors.New(fmt.Sprintf(errNoCollection, "tables")) }