linear-sdk-patterns

3
1
Source

TypeScript/JavaScript SDK patterns and best practices for Linear. Use when learning SDK idioms, implementing common patterns, or optimizing Linear API usage. Trigger with phrases like "linear SDK patterns", "linear best practices", "linear typescript", "linear API patterns", "linear SDK idioms".

Install

mkdir -p .claude/skills/linear-sdk-patterns && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5375" && unzip -o skill.zip -d .claude/skills/linear-sdk-patterns && rm skill.zip

Installs to .claude/skills/linear-sdk-patterns

About this skill

Linear SDK Patterns

Overview

Production patterns for @linear/sdk. The SDK wraps Linear's GraphQL API with strongly-typed models, cursor-based pagination (fetchNext()/fetchPrevious()), lazy-loaded relations, and typed error classes. Understanding these patterns avoids N+1 queries and rate limit waste.

Prerequisites

  • @linear/sdk installed
  • TypeScript project with strict: true
  • Understanding of async/await and GraphQL concepts

Instructions

Pattern 1: Client Singleton

import { LinearClient } from "@linear/sdk";

let _client: LinearClient | null = null;

export function getLinearClient(): LinearClient {
  if (!_client) {
    const apiKey = process.env.LINEAR_API_KEY;
    if (!apiKey) throw new Error("LINEAR_API_KEY is required");
    _client = new LinearClient({ apiKey });
  }
  return _client;
}

// For multi-user OAuth apps — one client per user
const clientCache = new Map<string, LinearClient>();

export function getClientForUser(userId: string, accessToken: string): LinearClient {
  if (!clientCache.has(userId)) {
    clientCache.set(userId, new LinearClient({ accessToken }));
  }
  return clientCache.get(userId)!;
}

Pattern 2: Cursor-Based Pagination

Linear uses Relay-style cursor pagination. The SDK provides fetchNext() and fetchPrevious() helpers, plus raw pageInfo for manual control.

// SDK built-in pagination helpers
const firstPage = await client.issues({ first: 50 });
console.log(`Page 1: ${firstPage.nodes.length} issues`);

if (firstPage.pageInfo.hasNextPage) {
  const secondPage = await firstPage.fetchNext();
  console.log(`Page 2: ${secondPage.nodes.length} issues`);
}

// Manual pagination with cursor — good for streaming all data
async function* paginateAll<T>(
  fetchPage: (cursor?: string) => Promise<{
    nodes: T[];
    pageInfo: { hasNextPage: boolean; endCursor: string };
  }>
): AsyncGenerator<T> {
  let cursor: string | undefined;
  let hasNext = true;

  while (hasNext) {
    const page = await fetchPage(cursor);
    for (const node of page.nodes) yield node;
    hasNext = page.pageInfo.hasNextPage;
    cursor = page.pageInfo.endCursor;
  }
}

// Stream all issues without loading everything into memory
for await (const issue of paginateAll(c => client.issues({ first: 50, after: c }))) {
  console.log(`${issue.identifier}: ${issue.title}`);
}

Pattern 3: Relation Loading (Avoiding N+1)

SDK models lazy-load relations. Accessing .assignee triggers a separate API call. Use raw GraphQL to batch-fetch relations in one request.

// LAZY (N+1 problem) — each .assignee is a separate API call
const issues = await client.issues({ first: 50 });
for (const issue of issues.nodes) {
  const assignee = await issue.assignee; // API call per issue!
  console.log(`${issue.identifier}: ${assignee?.name}`);
}

// BATCH (1 request) — use rawRequest for precise field selection
const response = await client.client.rawRequest(`
  query TeamIssues($teamKey: String!) {
    issues(first: 50, filter: { team: { key: { eq: $teamKey } } }) {
      nodes {
        id identifier title priority
        assignee { name email }
        state { name type }
        labels { nodes { name color } }
        project { name }
      }
    }
  }
`, { teamKey: "ENG" });

// PRE-RESOLVE — parallel resolution for a single issue
async function enrichIssue(issue: any) {
  const [assignee, state, team, labels] = await Promise.all([
    issue.assignee,
    issue.state,
    issue.team,
    issue.labels(),
  ]);
  return { ...issue, _assignee: assignee, _state: state, _team: team, _labels: labels.nodes };
}

Pattern 4: Filtering with Comparators

Linear supports eq, neq, in, nin, lt, lte, gt, gte, startsWith, contains, and logical and/or operators.

// High-priority open bugs
const bugs = await client.issues({
  first: 50,
  filter: {
    priority: { lte: 2 },
    state: { type: { nin: ["completed", "canceled"] } },
    labels: { name: { eq: "Bug" } },
    team: { key: { eq: "ENG" } },
  },
});

// OR logic — issues assigned to Alice or Bob
const filtered = await client.issues({
  filter: {
    or: [
      { assignee: { email: { eq: "[email protected]" } } },
      { assignee: { email: { eq: "[email protected]" } } },
    ],
    state: { type: { eq: "started" } },
  },
});

// Full-text search
const results = await client.issueSearch("authentication bug");

// Issues updated in the last 24 hours
const recent = await client.issues({
  filter: {
    updatedAt: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() },
  },
  orderBy: "updatedAt",
  first: 100,
});

Pattern 5: Type-Safe Error Handling

import { LinearError, InvalidInputLinearError } from "@linear/sdk";

type Result<T> = { ok: true; data: T } | { ok: false; error: string; retryable: boolean };

async function safeCall<T>(fn: () => Promise<T>): Promise<Result<T>> {
  try {
    return { ok: true, data: await fn() };
  } catch (error) {
    if (error instanceof InvalidInputLinearError) {
      return { ok: false, error: `Invalid input: ${error.message}`, retryable: false };
    }
    if (error instanceof LinearError) {
      const retryable = error.status === 429 || error.status === 503;
      return { ok: false, error: `[${error.status}] ${error.message}`, retryable };
    }
    return { ok: false, error: String(error), retryable: false };
  }
}

// Usage
const result = await safeCall(() => client.issue("issue-uuid"));
if (result.ok) {
  console.log(result.data.title);
} else if (result.retryable) {
  console.warn("Transient error, retry:", result.error);
}

Pattern 6: Custom GraphQL Client

Access the underlying LinearGraphQLClient for full control.

const graphQLClient = client.client;

// Set custom headers
graphQLClient.setHeader("X-Request-Id", crypto.randomUUID());

// Raw query with variables
const data = await graphQLClient.rawRequest(`
  query Cycle($id: String!) {
    cycle(id: $id) {
      id name startsAt endsAt
      issues { nodes { identifier title state { name } } }
    }
  }
`, { id: "cycle-uuid" });

// Batch mutations
const batchResult = await graphQLClient.rawRequest(`
  mutation BatchUpdate {
    a: issueUpdate(id: "id1", input: { priority: 1 }) { success }
    b: issueUpdate(id: "id2", input: { priority: 1 }) { success }
    c: issueUpdate(id: "id3", input: { priority: 1 }) { success }
  }
`);

Error Handling

ErrorCauseSolution
Cannot read properties of nullNullable relation not checkedUse (await issue.assignee)?.name
Type is not assignableSDK/TypeScript version mismatchUpdate @linear/sdk to latest
Promise rejection unhandledMissing try/catch on asyncWrap in safeCall() or .catch()
Query complexity too highToo many nested relationsUse rawRequest() with flat field selection

Examples

Create Issue with Full Metadata

const teams = await client.teams();
const eng = teams.nodes.find(t => t.key === "ENG")!;
const states = await eng.states();
const todo = states.nodes.find(s => s.type === "unstarted")!;
const labels = await client.issueLabels({ filter: { name: { eq: "Bug" } } });

await client.createIssue({
  teamId: eng.id,
  title: "Login page crashes on Safari",
  description: "## Steps to reproduce\n1. Open login in Safari 17\n2. Click Sign in\n3. Crash",
  stateId: todo.id,
  priority: 1,
  labelIds: [labels.nodes[0].id],
  estimate: 3,
});

Resources

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

11340

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

9033

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

18828

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

5519

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,6871,430

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,2711,336

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,5441,153

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,359809

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,266730

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,495685