From 224f50b7932d8f6c35cd180df29cf51222b330e4 Mon Sep 17 00:00:00 2001 From: "Daniel G. Taylor" Date: Wed, 27 Jul 2022 12:05:32 -0700 Subject: [PATCH] feat(graphql): add ignore prefixes config option --- graphql.go | 10 ++++++++++ graphql_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/graphql.go b/graphql.go index 1c923230..0bd77632 100644 --- a/graphql.go +++ b/graphql.go @@ -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{}) } diff --git a/graphql_test.go b/graphql_test.go index 7ecd71ac..fb5fc59a 100644 --- a/graphql_test.go +++ b/graphql_test.go @@ -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()) }