Graphql: constructing graphql schema using reflection

Created on 14 Oct 2019  路  6Comments  路  Source: graphql-go/graphql

I'm always shocked by the boilerplate I need to write to add simple structs to my schema.

What I did is: I started to write some helper methods to analyze my structs via reflection and generate the gql types from my go structs.

Looks like this:

type Model struct {
    Id        int64     `gorm:"type:bigserial;primary_key" json:"id"`
    CreatedAt time.Time `sql:"DEFAULT:NOW()" json:"createdAt"`
    UpdatedAt time.Time `json:"updatedAt"`
}

type IntegrationHttp struct {
    Model
    App   *model.AppInstance `gorm:"not null;foreignkey:id;association_foreignkey:AppId" json:"app"`
    AppId int64              `gorm:"not null" json:"appId"`

    Method  string `json:"method"`
    Url     string `json:"url"`
    Skipped string `json:"-"`
}

func TestNewTypeFromStruct(t *testing.T) {
    conf := schema.NewTypeFromStruct(IntegrationHttp{})

    assert.Equal(t, "IntegrationHttp", conf.Name())

    confFields := conf.Fields()
    assert.Equal(t, 7, len(confFields))
}

Yet it takes the fields names from the json tag, could be configurable as well.
I also added a custom tag gql where you can override the type of a field with e.g. gql:"type:String".

I can Imagine a bunch of more features. Since the code runs only once at startup time, I do not see any performance issues but reducing a lot of boilerplate code.

Now my questions are:

  • Is this kind of struct generation interesting for this library?
  • Is it interesting in general (I could start another repository)?

Or do you see any general issues with that and I should keep it private? Else I would love to share the implementation and would be happy to further improve it.

Most helpful comment

It would be cool to generate a gql-schema from the protobuf files.

All 6 comments

It would be cool to generate a gql-schema from the protobuf files.

Can you please share it? I'm in the middle of implementing that by myself and then I saw your port @Niondir

Yes, I can put something online. Meanwhile I switched to gqlgen, so I probably do not follow up on this anymore.

Here is what I have till now. It's just a start, feel free to use the code.

generic.zip

ok @Niondir,
Should I follow your github account or it's gonna be somewhere else?
If it wont be here, can you please send it to me? [email protected]

When you publish the code just link it here and maybe mention me somewhere in the credits :)

NewTypeFromStruct and NewInputTypeFromStruct are the entry points.

I had most problems with the order of dependencies between types during initialization. Some problems got already solved by using InputObjectConfigFieldMapThunk.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zbintliff picture zbintliff  路  3Comments

januszm picture januszm  路  6Comments

yhc44 picture yhc44  路  5Comments

conord33 picture conord33  路  6Comments

jiharal picture jiharal  路  5Comments