graphql
graphql copied to clipboard
constructing graphql schema using reflection
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.
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.
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.
See https://github.com/samsarahq/thunder