Skip to content

Commit

Permalink
feat(settings): add basic user settings schema
Browse files Browse the repository at this point in the history
  • Loading branch information
scottmckendry committed Aug 21, 2024
1 parent 6ef14e7 commit 2b871a2
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
74 changes: 74 additions & 0 deletions data/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ type User struct {
GithubID string
}

type UserSettings struct {
Mappings map[string]string
SearchEngine string
LeaderKey string
}

func NewStore(db *sql.DB) *Storage {
return &Storage{
db: db,
Expand Down Expand Up @@ -107,3 +113,71 @@ func buildUserFromGothUser(gothUser goth.User) *User {

return user
}

func (s *Storage) GetUserSettings(email string) *UserSettings {
settings := &UserSettings{}
settings.Mappings = getMappings(s.db, email)
settings = s.getGenericSettings(email, settings)

return settings
}

func getMappings(db *sql.DB, email string) map[string]string {
rows, err := db.Query(
`SELECT keymap, maps_to
FROM mappings
INNER JOIN users
ON mappings.user_id = users.id
WHERE users.email = ?`,
email,
)
if err != nil {
return nil
}
defer rows.Close()

mappings := make(map[string]string)
for rows.Next() {
var keymap, mapsTo string
err = rows.Scan(&keymap, &mapsTo)
if err != nil {
return nil
}

mappings[keymap] = mapsTo
}

return mappings
}

func (s *Storage) getGenericSettings(email string, settings *UserSettings) *UserSettings {
rows, err := s.db.Query(
`SELECT setting_key, setting_value
FROM user_settings
INNER JOIN users
ON user_settings.user_id = users.id
WHERE users.email = ?`,
email,
)
if err != nil {
return nil
}
defer rows.Close()

for rows.Next() {
var key, value string
err = rows.Scan(&key, &value)
if err != nil {
return nil
}

switch key {
case "SearchEngine":
settings.SearchEngine = value
case "LeaderKey":
settings.LeaderKey = value
}
}

return settings
}
24 changes: 24 additions & 0 deletions data/libsql.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,29 @@ func generateSchema(db *sql.DB) error {
return fmt.Errorf("Error creating users table: %v", err)
}

_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS mappings (
id INTEGER PRIMARY KEY,
user_id INTEGER,
keymap TEXT,
maps_to TEXT
);
`)
if err != nil {
return fmt.Errorf("Error creating mappings table: %v", err)
}

_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS user_settings (
id INTEGER PRIMARY KEY,
user_id INTEGER,
setting_key TEXT,
setting_value TEXT
);
`)
if err != nil {
return fmt.Errorf("Error creating user_settings table: %v", err)
}

return nil
}

0 comments on commit 2b871a2

Please sign in to comment.