PrintQueryResponse prints the query response in the desired format (human, json, csv)
(res *runtimev1.QueryResolverResponse)
| 813 | |
| 814 | // PrintQueryResponse prints the query response in the desired format (human, json, csv) |
| 815 | func (p *Printer) PrintQueryResponse(res *runtimev1.QueryResolverResponse) { |
| 816 | if len(res.Data) == 0 { |
| 817 | p.PrintfWarn("No data found\n") |
| 818 | return |
| 819 | } |
| 820 | |
| 821 | switch p.Format { |
| 822 | // Interceptor for human format |
| 823 | case FormatHuman: |
| 824 | headers := extractQueryHeaders(res.Schema) |
| 825 | rows := make([][]string, len(res.Data)) |
| 826 | |
| 827 | for i, row := range res.Data { |
| 828 | rows[i] = make([]string, len(headers)) |
| 829 | for j, field := range headers { |
| 830 | if val, ok := row.GetFields()[field]; ok { |
| 831 | rows[i][j] = p.FormatValue(val.AsInterface()) |
| 832 | } else { |
| 833 | rows[i][j] = "null" |
| 834 | } |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | tableprinter.New(p.dataOut()).Render(headers, rows, nil, false) |
| 839 | return |
| 840 | |
| 841 | // Interceptor for CSV format |
| 842 | case FormatCSV: |
| 843 | headers := extractQueryHeaders(res.Schema) |
| 844 | w := csv.NewWriter(p.dataOut()) |
| 845 | |
| 846 | if err := w.Write(headers); err != nil { |
| 847 | panic(fmt.Errorf("failed to write CSV headers: %w", err)) |
| 848 | } |
| 849 | |
| 850 | for _, row := range res.Data { |
| 851 | record := make([]string, len(headers)) |
| 852 | for i, field := range headers { |
| 853 | if val, ok := row.GetFields()[field]; ok { |
| 854 | record[i] = p.FormatValue(val.AsInterface()) |
| 855 | } else { |
| 856 | record[i] = "" |
| 857 | } |
| 858 | } |
| 859 | if err := w.Write(record); err != nil { |
| 860 | panic(fmt.Errorf("failed to write CSV row: %w", err)) |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | w.Flush() |
| 865 | if err := w.Error(); err != nil { |
| 866 | panic(fmt.Errorf("failed to flush CSV writer: %w", err)) |
| 867 | } |
| 868 | |
| 869 | return |
| 870 | default: |
| 871 | p.PrintData(res.Data) |
| 872 | } |
no test coverage detected