-
Notifications
You must be signed in to change notification settings - Fork 242
feat: add module to add operation name also as operationName field #3048
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
alepane21
wants to merge
3
commits into
main
Choose a base branch
from
ale/eng-9848-router-add-option-to-include-operationname-in-subgraph
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+236
−0
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| package module_test | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
| "sync" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
|
|
||
| custom_add_operation_name "github.com/wundergraph/cosmo/router-tests/modules/custom-add-operation-name" | ||
| "github.com/wundergraph/cosmo/router-tests/testenv" | ||
| "github.com/wundergraph/cosmo/router/core" | ||
| "github.com/wundergraph/cosmo/router/pkg/config" | ||
| ) | ||
|
|
||
| func TestAddOperationNameModule(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| t.Run("adds the client operation name to the origin request body", func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| cfg := config.Config{ | ||
| Graph: config.Graph{}, | ||
| Modules: map[string]any{ | ||
| "addOperationNameModule": custom_add_operation_name.AddOperationNameModule{}, | ||
| }, | ||
| } | ||
|
|
||
| var ( | ||
| mu sync.Mutex | ||
| capturedBodies [][]byte | ||
| ) | ||
|
|
||
| testenv.Run(t, &testenv.Config{ | ||
| Subgraphs: testenv.SubgraphsConfig{ | ||
| GlobalMiddleware: func(handler http.Handler) http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| body, err := io.ReadAll(r.Body) | ||
| require.NoError(t, err) | ||
|
|
||
| mu.Lock() | ||
| capturedBodies = append(capturedBodies, body) | ||
| mu.Unlock() | ||
|
|
||
| handler.ServeHTTP(w, r) | ||
| }) | ||
| }, | ||
| }, | ||
| RouterOptions: []core.Option{ | ||
| core.WithModulesConfig(cfg.Modules), | ||
| core.WithCustomModules(&custom_add_operation_name.AddOperationNameModule{}), | ||
| }, | ||
| ModifyEngineExecutionConfiguration: func(conf *config.EngineExecutionConfiguration) { | ||
| conf.EnableSubgraphFetchOperationName = true | ||
| }, | ||
| }, func(t *testing.T, xEnv *testenv.Environment) { | ||
| res, err := xEnv.MakeGraphQLRequest(testenv.GraphQLRequest{ | ||
| Query: `query MyQuery { employees { id } }`, | ||
| OperationName: json.RawMessage(`"MyQuery"`), | ||
| }) | ||
| require.NoError(t, err) | ||
| require.Equal(t, 200, res.Response.StatusCode) | ||
|
|
||
| mu.Lock() | ||
| defer mu.Unlock() | ||
| require.Len(t, capturedBodies, 1) | ||
|
|
||
| var payload map[string]json.RawMessage | ||
| require.NoError(t, json.Unmarshal(capturedBodies[0], &payload)) | ||
|
|
||
| // The operationName property must sit at the same level as the query property | ||
| require.Contains(t, payload, "query") | ||
| require.Contains(t, payload, "operationName") | ||
|
|
||
| var operationName string | ||
| require.NoError(t, json.Unmarshal(payload["operationName"], &operationName)) | ||
| assert.Equal(t, "MyQuery__employees__0", operationName) | ||
| }) | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| package module | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "io" | ||
| "net/http" | ||
|
|
||
| "github.com/wundergraph/astjson" | ||
| "github.com/wundergraph/cosmo/router/core" | ||
| "github.com/wundergraph/graphql-go-tools/v2/pkg/astparser" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| const moduleID = "addOperationNameModule" | ||
|
|
||
| type AddOperationNameModule struct { | ||
| Logger *zap.Logger | ||
| } | ||
|
|
||
| func (m *AddOperationNameModule) Provision(ctx *core.ModuleContext) error { | ||
|
|
||
| // Assign the logger to the module for non-request related logging | ||
| m.Logger = ctx.Logger | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (m *AddOperationNameModule) OnOriginRequest(request *http.Request, ctx core.RequestContext) (*http.Request, *http.Response) { | ||
| if request.Body == nil { | ||
| return request, nil | ||
| } | ||
| body, err := io.ReadAll(request.Body) | ||
| _ = request.Body.Close() | ||
| if err != nil { | ||
| m.Logger.Error("addOperationNameModule: failed to read origin request body", zap.Error(err)) | ||
| return request, nil | ||
| } | ||
|
|
||
| // Best-effort: on any parse failure, forward the original body unchanged. | ||
| if payload, err := astjson.ParseBytes(body); err == nil { | ||
| doc, report := astparser.ParseGraphqlDocumentBytes(payload.GetStringBytes("query")) | ||
| if !report.HasErrors() && len(doc.OperationDefinitions) == 1 { | ||
| if name := doc.Input.ByteSlice(doc.OperationDefinitions[0].Name); len(name) > 0 { | ||
| payload.Set(nil, "operationName", astjson.StringValueBytes(nil, name)) | ||
| body = payload.MarshalTo(nil) | ||
| } | ||
| } | ||
| } | ||
| request.Body = io.NopCloser(bytes.NewReader(body)) | ||
| request.ContentLength = int64(len(body)) | ||
| request.GetBody = func() (io.ReadCloser, error) { | ||
| return io.NopCloser(bytes.NewReader(body)), nil | ||
| } | ||
| return request, nil | ||
| } | ||
|
|
||
| func (m *AddOperationNameModule) Module() core.ModuleInfo { | ||
| return core.ModuleInfo{ | ||
| // This is the ID of your module, it must be unique | ||
| ID: moduleID, | ||
| // The priority of your module, lower numbers are executed first | ||
| Priority: 1, | ||
| New: func() core.Module { | ||
| return &AddOperationNameModule{} | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // Interface guard | ||
| var ( | ||
| _ core.EnginePreOriginHandler = (*AddOperationNameModule)(nil) | ||
| _ core.Provisioner = (*AddOperationNameModule)(nil) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| package module | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "io" | ||
| "net/http" | ||
|
|
||
| "github.com/wundergraph/astjson" | ||
| "github.com/wundergraph/cosmo/router/core" | ||
| "github.com/wundergraph/graphql-go-tools/v2/pkg/astparser" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| func init() { | ||
| // Register your module here | ||
| core.RegisterModule(&AddOperationNameModule{}) | ||
| } | ||
|
|
||
| const moduleID = "addOperationNameModule" | ||
|
|
||
| type AddOperationNameModule struct { | ||
| Logger *zap.Logger | ||
| } | ||
|
|
||
| func (m *AddOperationNameModule) Provision(ctx *core.ModuleContext) error { | ||
|
|
||
| // Assign the logger to the module for non-request related logging | ||
| m.Logger = ctx.Logger | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (m *AddOperationNameModule) OnOriginRequest(request *http.Request, ctx core.RequestContext) (*http.Request, *http.Response) { | ||
| if request.Body == nil { | ||
| return request, nil | ||
| } | ||
| body, err := io.ReadAll(request.Body) | ||
| _ = request.Body.Close() | ||
| if err != nil { | ||
| m.Logger.Error("addOperationNameModule: failed to read origin request body", zap.Error(err)) | ||
| return request, nil | ||
| } | ||
|
|
||
| // Best-effort: on any parse failure, forward the original body unchanged. | ||
| if payload, err := astjson.ParseBytes(body); err == nil { | ||
| doc, report := astparser.ParseGraphqlDocumentBytes(payload.GetStringBytes("query")) | ||
| if !report.HasErrors() && len(doc.OperationDefinitions) == 1 { | ||
| if name := doc.Input.ByteSlice(doc.OperationDefinitions[0].Name); len(name) > 0 { | ||
| payload.Set(nil, "operationName", astjson.StringValueBytes(nil, name)) | ||
| body = payload.MarshalTo(nil) | ||
| } | ||
| } | ||
| } | ||
| request.Body = io.NopCloser(bytes.NewReader(body)) | ||
| request.ContentLength = int64(len(body)) | ||
| request.GetBody = func() (io.ReadCloser, error) { | ||
| return io.NopCloser(bytes.NewReader(body)), nil | ||
| } | ||
| return request, nil | ||
| } | ||
|
|
||
| func (m *AddOperationNameModule) Module() core.ModuleInfo { | ||
| return core.ModuleInfo{ | ||
| // This is the ID of your module, it must be unique | ||
| ID: moduleID, | ||
| // The priority of your module, lower numbers are executed first | ||
| Priority: 1, | ||
| New: func() core.Module { | ||
| return &AddOperationNameModule{} | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // Interface guard | ||
| var ( | ||
| _ core.EnginePreOriginHandler = (*AddOperationNameModule)(nil) | ||
| _ core.Provisioner = (*AddOperationNameModule)(nil) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: wundergraph/cosmo
Length of output: 340
🏁 Script executed:
Repository: wundergraph/cosmo
Length of output: 2748
Restore
r.Bodybefore calling the wrapped handler.io.ReadAll(r.Body)drains the request, so the downstream subgraph handler receives an empty body and the test no longer exercises real GraphQL execution. Rewind it withio.NopCloser(bytes.NewReader(body)), and consider asserting the response payload too.🤖 Prompt for AI Agents