---
title: "Examples"
description: "Code examples for common TraceRTM JavaScript SDK use cases"
---

# Examples

Practical code examples demonstrating common use cases with the TraceRTM JavaScript SDK.

## Quick Examples

### Initialize and List Projects

```typescript
import { TraceRTMClient } from "@tracertm/sdk";

const client = new TraceRTMClient({
  apiKey: process.env.TRACERTM_API_KEY,
});

const projects = await client.projects.list();
console.log(`Found ${projects.total} projects`);
```

### Create Project with Requirements

```typescript
// Create project
const project = await client.projects.create({
  name: "E-Commerce Platform",
  key: "ECOM",
});

// Add requirements
const requirements = await client.items.bulkCreate([
  {
    projectId: project.id,
    type: "requirement",
    title: "User Registration",
    priority: "high",
    tags: ["auth"],
  },
  {
    projectId: project.id,
    type: "requirement",
    title: "Shopping Cart",
    priority: "high",
    tags: ["cart"],
  },
  {
    projectId: project.id,
    type: "requirement",
    title: "Checkout Flow",
    priority: "critical",
    tags: ["checkout"],
  },
]);

console.log(`Created ${requirements.length} requirements`);
```

### Link Requirements to Tests

```typescript
// Get uncovered requirements
const coverage = await client.reports.coverage({
  projectId: "proj_123",
  sourceType: "requirement",
  targetType: "test_case",
});

// Create test cases for uncovered requirements
for (const req of coverage.uncoveredItems) {
  const test = await client.items.create({
    projectId: "proj_123",
    type: "test_case",
    title: `Test: ${req.title}`,
    priority: "high",
  });

  await client.links.create({
    sourceId: req.id,
    targetId: test.id,
    type: "verified_by",
  });
}
```

---

## Project Management

### Create and Configure Project

```typescript
const project = await client.projects.create({
  name: "Medical Device Software",
  key: "MDS",
  description: "FDA-regulated medical device requirements",
  settings: {
    allowedItemTypes: ["requirement", "test_case", "risk", "decision"],
    requireApproval: true,
  },
});
```

### Clone Project Structure

```typescript
async function cloneProjectStructure(sourceId: string, newName: string) {
  const source = await client.projects.get(sourceId);

  // Create new project
  const newProject = await client.projects.create({
    name: newName,
    key: `${source.key}_COPY`,
    description: `Clone of ${source.name}`,
  });

  // Copy items
  const items = await client.items.list({
    projectId: sourceId,
    limit: 100,
  });

  const idMap = new Map<string, string>();

  for (const item of items.data) {
    const newItem = await client.items.create({
      projectId: newProject.id,
      type: item.type,
      title: item.title,
      description: item.description,
      priority: item.priority,
      tags: item.tags,
    });
    idMap.set(item.id, newItem.id);
  }

  // Copy links
  const links = await client.links.list({ projectId: sourceId });

  for (const link of links.data) {
    const newSourceId = idMap.get(link.sourceId);
    const newTargetId = idMap.get(link.targetId);

    if (newSourceId && newTargetId) {
      await client.links.create({
        sourceId: newSourceId,
        targetId: newTargetId,
        type: link.type,
      });
    }
  }

  return newProject;
}
```

---

## Item Operations

### Filter Items by Multiple Criteria

```typescript
// High-priority bugs assigned to current user
const myBugs = await client.items.list({
  projectId: "proj_123",
  type: "bug",
  priority: ["critical", "high"],
  assigneeId: "user_me",
  statusCategory: "in_progress",
});

// Requirements updated in last 7 days
const recentRequirements = await client.items.list({
  projectId: "proj_123",
  type: "requirement",
  updatedAfter: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
  sort: "updated_at",
  order: "desc",
});
```

### Batch Status Update

```typescript
async function approveAllReviewed(projectId: string) {
  const reviewed = await client.items.list({
    projectId,
    status: "reviewed",
  });

  const updates = reviewed.data.map((item) => ({
    id: item.id,
    status: "approved",
  }));

  const updated = await client.items.bulkUpdate(updates);
  console.log(`Approved ${updated.length} items`);
}
```

### Create Item Hierarchy

```typescript
async function createEpicWithStories(projectId: string) {
  // Create epic
  const epic = await client.items.create({
    projectId,
    type: "epic",
    title: "User Authentication System",
    priority: "high",
  });

  // Create user stories under epic
  const stories = [
    "As a user, I can register with email",
    "As a user, I can login with password",
    "As a user, I can reset my password",
    "As a user, I can enable 2FA",
  ];

  const createdStories = await Promise.all(
    stories.map((title) =>
      client.items.create({
        projectId,
        type: "user_story",
        title,
        parentId: epic.id,
        priority: "medium",
      })
    )
  );

  // Link stories to epic
  await Promise.all(
    createdStories.map((story) =>
      client.links.create({
        sourceId: epic.id,
        targetId: story.id,
        type: "parent_of",
      })
    )
  );

  return { epic, stories: createdStories };
}
```

---

## Traceability

### Build Complete Trace Chain

```typescript
async function buildTraceChain(projectId: string) {
  // Requirements -> User Stories -> Test Cases
  const req = await client.items.create({
    projectId,
    type: "requirement",
    title: "REQ-001: Secure Login",
    priority: "high",
  });

  const story = await client.items.create({
    projectId,
    type: "user_story",
    title: "US-001: Login with email/password",
  });

  const test = await client.items.create({
    projectId,
    type: "test_case",
    title: "TC-001: Verify login success",
  });

  // Create trace chain
  await client.links.create({
    sourceId: req.id,
    targetId: story.id,
    type: "traces_to",
  });

  await client.links.create({
    sourceId: story.id,
    targetId: test.id,
    type: "verified_by",
  });

  return { req, story, test };
}
```

### Find Orphaned Items

```typescript
async function findOrphanedItems(projectId: string) {
  const items = await client.items.list({
    projectId,
    include: ["links"],
  });

  const orphaned = items.data.filter(
    (item) => !item.links || item.links.length === 0
  );

  console.log(`Found ${orphaned.length} items without links`);
  return orphaned;
}
```

### Impact Analysis Report

```typescript
async function generateImpactReport(itemId: string) {
  const impact = await client.reports.impactAnalysis({
    itemId,
    depth: 5,
    direction: "both",
  });

  console.log(`Impact Analysis for: ${impact.rootItem.title}`);
  console.log(`Total impacted items: ${impact.totalImpacted}`);

  // Group by distance
  const byDistance = new Map<number, typeof impact.impactedItems>();

  for (const item of impact.impactedItems) {
    const group = byDistance.get(item.distance) || [];
    group.push(item);
    byDistance.set(item.distance, group);
  }

  for (const [distance, items] of byDistance) {
    console.log(`\nDistance ${distance}:`);
    for (const { item, direction } of items) {
      console.log(`  [${direction}] ${item.type}: ${item.title}`);
    }
  }

  return impact;
}
```

---

## Reporting

### Coverage Dashboard

```typescript
async function getCoverageDashboard(projectId: string) {
  const [reqToTest, storyToTest, reqToStory] = await Promise.all([
    client.reports.coverage({
      projectId,
      sourceType: "requirement",
      targetType: "test_case",
    }),
    client.reports.coverage({
      projectId,
      sourceType: "user_story",
      targetType: "test_case",
    }),
    client.reports.coverage({
      projectId,
      sourceType: "requirement",
      targetType: "user_story",
    }),
  ]);

  return {
    requirementTestCoverage: reqToTest.coveragePercent,
    storyTestCoverage: storyToTest.coveragePercent,
    requirementStoryCoverage: reqToStory.coveragePercent,
    uncoveredRequirements: reqToTest.uncoveredItems.length,
    uncoveredStories: storyToTest.uncoveredItems.length,
  };
}
```

### Export Traceability Matrix

```typescript
async function exportMatrix(projectId: string) {
  const matrix = await client.reports.traceabilityMatrix({
    projectId,
    sourceTypes: ["requirement"],
    targetTypes: ["test_case"],
    format: "json",
  });

  // Generate CSV
  const rows = ["Source,Target,Link Type,Status"];

  for (const row of matrix.rows) {
    for (const cell of row.targets) {
      if (cell.linked) {
        for (const link of cell.links) {
          rows.push(
            `"${row.source.title}","${cell.target.title}","${link.type}","${cell.target.status}"`
          );
        }
      }
    }
  }

  return rows.join("\n");
}
```

---

## Search and Discovery

### Advanced Search

```typescript
async function searchAcrossProjects(query: string) {
  const results = await client.search.items({
    query,
    types: ["requirement", "user_story"],
    highlight: true,
  });

  for (const hit of results.items) {
    console.log(`[${hit.score.toFixed(2)}] ${hit.item.title}`);
    if (hit.highlights.title) {
      console.log(`  Match: ${hit.highlights.title[0]}`);
    }
  }

  return results;
}
```

### Find Similar Items

```typescript
async function findSimilar(itemId: string) {
  const item = await client.items.get(itemId);

  // Search for items with similar title keywords
  const keywords = item.title.split(" ").filter((w) => w.length > 3);

  const results = await client.search.items({
    query: keywords.join(" "),
    projectIds: [item.projectId],
    types: [item.type],
    limit: 10,
  });

  // Filter out the original item
  return results.items.filter((hit) => hit.item.id !== itemId);
}
```

---

## Related Documentation

- [Basic Examples](/docs/api-reference/sdks/javascript/basic-examples) - Simple examples
- [Advanced Examples](/docs/api-reference/sdks/javascript/advanced-examples) - Complex patterns
- [API Reference](/docs/api-reference/sdks/javascript/api-reference) - Full API docs
