Skip to content

Commit

Permalink
update config (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Aug 6, 2023
1 parent 9b064b4 commit 5a4da35
Showing 1 changed file with 30 additions and 16 deletions.
46 changes: 30 additions & 16 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ const (
ExpirationKey ConfKey = "expiration"
)

func (k ConfKey) isTokenKey() bool {
return k == AccessTokenKey || k == RefreshTokenKey || k == ExpirationKey
}

func (k ConfKey) isClientKey() bool {
return k == SpotifyIDKey || k == SpotifySecretKey || k == OpenAIAPIKey
}

func newConfig() *Config {
return &Config{
tokenViper: viper.New(),
Expand Down Expand Up @@ -108,10 +116,18 @@ func (c *Config) Load() error {
return nil
}

func (c *Config) SetToken(token *oauth2.Token) error {
c.tokenViper.Set(string(AccessTokenKey), token.AccessToken)
c.tokenViper.Set(string(RefreshTokenKey), token.RefreshToken)
c.tokenViper.Set(string(ExpirationKey), token.Expiry.Unix())
func (c *Config) Set(key ConfKey, value any) error {
if key.isTokenKey() {
return c.setToken(key, value)
} else if key.isClientKey() {
return c.setClient(key, value)
}

return fmt.Errorf("fail to set config. invalid key: %s", key)
}

func (c *Config) setToken(key ConfKey, value any) error {
c.tokenViper.Set(string(key), value)

if err := c.tokenViper.WriteConfig(); err != nil {
return fmt.Errorf("fail to write token config: %v", err)
Expand All @@ -120,6 +136,16 @@ func (c *Config) SetToken(token *oauth2.Token) error {
return nil
}

func (c *Config) setClient(key ConfKey, value any) error {
c.clientViper.Set(string(key), value)

if err := c.clientViper.WriteConfig(); err != nil {
return fmt.Errorf("fail to write token config: %v", err)
}

return nil
}

func (c *Config) GetToken() *oauth2.Token {
accessToken := c.tokenViper.GetString(string(AccessTokenKey))
refreshToken := c.tokenViper.GetString(string(RefreshTokenKey))
Expand All @@ -135,18 +161,6 @@ func (c *Config) GetToken() *oauth2.Token {
}
}

func (c *Config) SetClient(spotifyID, spotifySecret, openAIApiKey string) error {
c.clientViper.Set(string(spotifyID), spotifyID)
c.clientViper.Set(string(spotifySecret), spotifySecret)
c.clientViper.Set(string(openAIApiKey), openAIApiKey)

if err := c.clientViper.WriteConfig(); err != nil {
return fmt.Errorf("fail to write client config: %v", err)
}

return nil
}

func (c *Config) IsClientValid() bool {
spotifyID := c.clientViper.GetString(string(SpotifyIDKey))
spotifySecret := c.clientViper.GetString(string(SpotifySecretKey))
Expand Down

0 comments on commit 5a4da35

Please sign in to comment.