feat(graphql): add ignore prefixes config option

This commit is contained in:
Daniel G. Taylor 2022-07-27 12:05:32 -07:00
parent 2754f42ebc
commit 224f50b793
No known key found for this signature in database
GPG key ID: 74AE195C5112E534
2 changed files with 35 additions and 0 deletions

View file

@ -40,6 +40,10 @@ type GraphQLConfig struct {
// `GraphQLDefaultPaginator` is used.
Paginator GraphQLPaginator
// IgnorePrefixes defines path prefixes which should be ignored by the
// GraphQL model generator.
IgnorePrefixes []string
// known keeps track of known structs since they can only be defined once
// per GraphQL endpoint. If used by multiple HTTP operations, they must
// reference the same struct converted to GraphQL schema.
@ -374,7 +378,13 @@ func (r *Router) EnableGraphQL(config *GraphQLConfig) {
config.costMap = gqlcost.CostMap{}
config.paginatorType = reflect.TypeOf(config.Paginator).Elem()
outer:
for _, resource := range resources {
for _, prefix := range config.IgnorePrefixes {
if strings.HasPrefix(resource.path, prefix) {
continue outer
}
}
r.handleResource(config, "Query", fields, resource, map[string]bool{})
}

View file

@ -194,8 +194,15 @@ func TestGraphQL(t *testing.T) {
ctx.WriteModel(http.StatusOK, categories[input.CategoryID].products[input.ProductID].stores[input.StoreID])
})
app.Resource("/ignored").Get("get-ignored", "doc",
NewResponse(http.StatusOK, "").Model(struct{ ID string }{}),
).Run(func(ctx Context) {
ctx.WriteHeader(http.StatusOK)
})
app.EnableGraphQL(&GraphQLConfig{
ComplexityLimit: 250,
IgnorePrefixes: []string{"/ignored"},
})
query := strings.Replace(strings.Replace(`{
@ -304,4 +311,22 @@ data:
id: target
url: https://www.target.com/
`, "\t", " ", -1), w.Body.String())
// Confirm expected top-level fields in the query API.
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, "/graphql?query={__schema{queryType{fields{name}}}}", nil)
app.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.YAMLEq(t, strings.Replace(`data:
__schema:
queryType:
fields:
- name: categories
- name: categoriesItem
- name: products
- name: productsItem
- name: stores
- name: storesItem
`, "\t", " ", -1), w.Body.String())
}