FusionAuth / fusionauth-client-builder

The FusionAuth client library builder
https://fusionauth.io/
Apache License 2.0
6 stars 24 forks source link

feat: go: implements stringer interface for enums. #39

Closed matthewhartstonge closed 2 years ago

matthewhartstonge commented 2 years ago

Being a lazy developer plugging into other systems (i.e. terraform) I want to be able to get string representations of enums, and IDE autocomplete using:

fusionauth.GrantType_ClientCredentials.String()

Instead of having to manually typecast every enum:

string(fusionauth.GrantType_ClientCredentials)

This will also enable being able to be a bit more smart enum based functions by being able to cast enums to the Stringer interface to do things over multiple types. As a trivial example:

package main

import (
    "fmt"
    "strings"
)

type EventType string

func (e EventType) String() string {
    return string(e)
}

const (
    // ...
    EventType_UserUpdate                     EventType = "user.update"
    EventType_UserUpdateComplete             EventType = "user.update.complete"
    EventType_Test                           EventType = "test"
)

func enumsToStringList(enums ...fmt.Stringer) string {
    var enumStrArr []string
    for _, enum := range enums {
        enumStrArr = append(enumStrArr, enum.String())
    }

    return strings.Join(enumStrArr, ", ")
}

func main() {
    eventsList := enumsToStringList(
        EventType_UserUpdate,
        EventType_UserUpdateComplete,
        EventType_Test,
    )
    fmt.Printf("Enabled events: %s", eventsList)
}

started from: https://github.com/FusionAuth/go-client/pull/59

mooreds commented 2 years ago

Thanks for the PR, @matthewhartstonge This looks quite go-ish ( included in the go tour https://tour.golang.org/methods/18 for example ).

Can you please add a test ( https://github.com/FusionAuth/go-client/blob/master/pkg/fusionauth/Client_test.go or https://github.com/FusionAuth/go-client/blob/master/pkg/fusionauth/Domain_test.go are the right places).

matthewhartstonge commented 2 years ago

Hey @mooreds, i'm wondering if it might be better to generate the tests programmatically for this?

Otherwise you may need to manually maintain a list of enums to iterate over and test for interface conformance.

i.e.

// domain_test.go
import "testing"

func Test_${d.type}ImplementsStringer(t *testing.T) {
  enum := ${d.type}("Test")
  if _, ok := enum.(fmt.Stringer); !ok {
    t.Errorf("${d.type} does not implement stringer interface\n")
  }
}
mooreds commented 2 years ago

Good point. I'll take a look at using something like what you suggested.

robotdan commented 2 years ago

Approved https://github.com/FusionAuth/fusionauth-client-builder/pull/42#pullrequestreview-845159138