buildDatabaseQuery creates a new GraphQL query containing only the specified root fields. It parses the original query, filters to include only the given fields, and reconstructs a valid GraphQL query string.
(rootFields []string)
| 540 | // It parses the original query, filters to include only the given fields, and reconstructs |
| 541 | // a valid GraphQL query string. |
| 542 | func (s *gstate) buildDatabaseQuery(rootFields []string) ([]byte, error) { |
| 543 | op, err := graph.Parse(s.r.query) |
| 544 | if err != nil { |
| 545 | return nil, fmt.Errorf("failed to parse query: %w", err) |
| 546 | } |
| 547 | |
| 548 | // Build a set of allowed root field names |
| 549 | allowed := make(map[string]bool, len(rootFields)) |
| 550 | for _, f := range rootFields { |
| 551 | allowed[f] = true |
| 552 | } |
| 553 | |
| 554 | // Find the root field IDs we want to keep |
| 555 | keepFieldIDs := make(map[int32]bool) |
| 556 | for _, f := range op.Fields { |
| 557 | if f.ParentID == -1 && allowed[f.Name] { |
| 558 | keepFieldIDs[f.ID] = true |
| 559 | // Also mark all descendants |
| 560 | markDescendants(op.Fields, f.ID, keepFieldIDs) |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | // Reconstruct query with only the selected fields |
| 565 | var buf bytes.Buffer |
| 566 | |
| 567 | // Write operation type and name |
| 568 | switch op.Type { |
| 569 | case graph.OpQuery: |
| 570 | buf.WriteString("query") |
| 571 | case graph.OpMutate: |
| 572 | buf.WriteString("mutation") |
| 573 | case graph.OpSub: |
| 574 | buf.WriteString("subscription") |
| 575 | } |
| 576 | |
| 577 | if op.Name != "" { |
| 578 | buf.WriteString(" ") |
| 579 | buf.WriteString(op.Name) |
| 580 | } |
| 581 | |
| 582 | // Write variable definitions if any |
| 583 | if len(op.VarDef) > 0 { |
| 584 | buf.WriteString("(") |
| 585 | for i, v := range op.VarDef { |
| 586 | if i > 0 { |
| 587 | buf.WriteString(", ") |
| 588 | } |
| 589 | buf.WriteString("$") |
| 590 | buf.WriteString(v.Name) |
| 591 | // We don't have type info, so we'll rely on the compiler to infer |
| 592 | } |
| 593 | buf.WriteString(")") |
| 594 | } |
| 595 | |
| 596 | buf.WriteString(" { ") |
| 597 | |
| 598 | // Write the selected root fields |
| 599 | writeFieldsRecursive(&buf, op.Fields, -1, keepFieldIDs) |
no test coverage detected