All files / src/graphql DynamicWorkItemsQuery.ts

89.39% Statements 59/66
88.46% Branches 23/26
78.26% Functions 18/23
89.23% Lines 58/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 2801x     1x                                     1x       25x                         6x     6x 13x     6x                 6x   6x                                                       6x                   8x   8x 13x 13x 12x       8x             14x 14x   14x 1x       13x   13x 1x     12x                       21x   29x     21x             21x     21x 7x 4x 2x 2x   2x             21x 21x 17x       4x 7x   5x 3x       4x       9x 8x                     1x       5x 5x                             3x 3x                             3x   3x 3x     3x 2x     3x                   1x                                           1x            
import { gql } from "graphql-tag";
import { TypedDocumentNode } from "@graphql-typed-document-node/core";
import { SchemaIntrospector, FieldInfo } from "../services/SchemaIntrospector";
import { logger } from "../logger";
 
export interface DynamicWorkItem {
  id: string;
  iid: string;
  title: string;
  description?: string;
  state: string;
  workItemType: {
    id: string;
    name: string;
  };
  createdAt: string;
  updatedAt: string;
  closedAt?: string;
  webUrl: string;
  widgets: Array<{ type: string; [key: string]: unknown }>;
}
 
export class DynamicWorkItemsQueryBuilder {
  private schemaIntrospector: SchemaIntrospector;
 
  constructor(schemaIntrospector: SchemaIntrospector) {
    this.schemaIntrospector = schemaIntrospector;
  }
 
  /**
   * Build a safe WorkItems query based on available schema
   */
  public buildWorkItemsQuery(
    requestedWidgets?: string[]
  ): TypedDocumentNode<
    { group: { workItems: { nodes: DynamicWorkItem[] } } },
    { groupPath: string; types?: string[]; first?: number; after?: string }
  > {
    // Use all available widgets if none specified
    const widgets = requestedWidgets ?? this.schemaIntrospector.getAvailableWidgetTypes();
 
    // Filter to only widgets that are actually available
    const availableWidgets = widgets.filter(widget =>
      this.schemaIntrospector.isWidgetTypeAvailable(widget)
    );
 
    logger.info(
      {
        requested: widgets.length,
        available: availableWidgets.length,
        widgetTypes: availableWidgets.slice(0, 5),
      },
      "Building dynamic WorkItems query"
    );
 
    const widgetFragments = this.buildWidgetFragments(availableWidgets);
 
    const query = gql`
      query GetWorkItems($groupPath: ID!, $types: [IssueType!], $first: Int, $after: String) {
        group(fullPath: $groupPath) {
          workItems(types: $types, first: $first, after: $after) {
            nodes {
              id
              iid
              title
              description
              state
              workItemType {
                id
                name
              }
              createdAt
              updatedAt
              closedAt
              webUrl
              widgets {
                type
                ${widgetFragments}
              }
            }
          }
        }
      }
    `;
 
    return query as TypedDocumentNode<
      { group: { workItems: { nodes: DynamicWorkItem[] } } },
      { groupPath: string; types?: string[]; first?: number; after?: string }
    >;
  }
 
  /**
   * Build widget fragments based on schema-validated fields
   */
  private buildWidgetFragments(widgetTypes: string[]): string {
    const fragments: string[] = [];
 
    for (const widgetType of widgetTypes) {
      const fragment = this.buildWidgetFragment(widgetType);
      if (fragment) {
        fragments.push(fragment);
      }
    }
 
    return fragments.join("\n");
  }
 
  /**
   * Build a single widget fragment with validated fields
   */
  private buildWidgetFragment(widgetType: string): string | null {
    const typeName = this.getWidgetTypeName(widgetType);
    const fields = this.schemaIntrospector.getFieldsForType(typeName);
 
    if (fields.length === 0) {
      return null;
    }
 
    // Build safe field selections
    const safeFields = this.buildSafeFields(widgetType, fields);
 
    if (safeFields.length === 0) {
      return null;
    }
 
    return `
      ... on ${typeName} {
        ${safeFields.join("\n        ")}
      }
    `;
  }
 
  /**
   * Convert widget type to GraphQL type name
   */
  private getWidgetTypeName(widgetType: string): string {
    // Convert SNAKE_CASE to PascalCase
    const pascalCase = widgetType
      .split("_")
      .map(part => part.charAt(0) + part.slice(1).toLowerCase())
      .join("");
 
    return `WorkItemWidget${pascalCase}`;
  }
 
  /**
   * Build safe field selections for a widget type
   */
  private buildSafeFields(widgetType: string, fields: FieldInfo[]): string[] {
    const safeFields: string[] = [];
 
    // Widget-specific field mappings
    const widgetFieldMappings: Record<string, () => string[]> = {
      ASSIGNEES: () => this.buildAssigneesFields(),
      LABELS: () => this.buildLabelsFields(),
      MILESTONE: () => this.buildMilestoneFields(),
      DESCRIPTION: () => this.buildDescriptionFields(),
      START_AND_DUE_DATE: () => ["startDate", "dueDate"],
      WEIGHT: () => ["weight"],
      TIME_TRACKING: () => ["timeEstimate", "totalTimeSpent"],
      HEALTH_STATUS: () => ["healthStatus"],
      COLOR: () => ["color"],
      NOTIFICATIONS: () => ["subscribed"],
    };
 
    const mapper = widgetFieldMappings[widgetType];
    if (mapper) {
      return mapper();
    }
 
    // Default: include only scalar/enum fields
    for (const field of fields) {
      if (field.name === "type") continue; // Skip type field as it's already included
 
      if (field.type?.kind === "SCALAR" || field.type?.kind === "ENUM") {
        safeFields.push(field.name);
      }
    }
 
    return safeFields;
  }
 
  private buildAssigneesFields(): string[] {
    if (this.schemaIntrospector.hasField("WorkItemWidgetAssignees", "assignees")) {
      return [
        "assignees {",
        "  nodes {",
        "    id",
        "    username",
        "    name",
        "    avatarUrl",
        "  }",
        "}",
      ];
    }
    return [];
  }
 
  private buildLabelsFields(): string[] {
    Eif (this.schemaIntrospector.hasField("WorkItemWidgetLabels", "labels")) {
      return [
        "labels {",
        "  nodes {",
        "    id",
        "    title",
        "    color",
        "    description",
        "  }",
        "}",
      ];
    }
    return [];
  }
 
  private buildMilestoneFields(): string[] {
    Eif (this.schemaIntrospector.hasField("WorkItemWidgetMilestone", "milestone")) {
      return [
        "milestone {",
        "  id",
        "  title",
        "  state",
        "  dueDate",
        "  startDate",
        "  webPath",
        "}",
      ];
    }
    return [];
  }
 
  private buildDescriptionFields(): string[] {
    const fields = ["description"];
 
    Eif (this.schemaIntrospector.hasField("WorkItemWidgetDescription", "descriptionHtml")) {
      fields.push("descriptionHtml");
    }
 
    if (this.schemaIntrospector.hasField("WorkItemWidgetDescription", "edited")) {
      fields.push("edited");
    }
 
    return fields;
  }
 
  /**
   * Build a minimal query for basic testing
   */
  public buildMinimalQuery(): TypedDocumentNode<
    { group: { workItems: { nodes: DynamicWorkItem[] } } },
    { groupPath: string; first?: number; after?: string }
  > {
    const query = gql`
      query GetWorkItemsMinimal($groupPath: ID!, $first: Int, $after: String) {
        group(fullPath: $groupPath) {
          workItems(first: $first, after: $after) {
            nodes {
              id
              iid
              title
              state
              workItemType {
                id
                name
              }
              widgets {
                type
              }
            }
          }
        }
      }
    `;
 
    return query as TypedDocumentNode<
      { group: { workItems: { nodes: DynamicWorkItem[] } } },
      { groupPath: string; first?: number; after?: string }
    >;
  }
}