Skill站外收录 @skilllib/skill-2117939930272413370
linear-sdk-patterns
提供 Linear API 的 TypeScript 集成最佳实践,涵盖客户端单例管理、分页数据迭代、健壮错误处理、批量操作优化、智能缓存策略及类型安全的查询构造能力,适用于构建高可靠性线性工作流系统。
软件开发 AI 技能
Skills.MD
# Linear SDK Patterns
## Overview
Essential patterns and best practices for working with the Linear SDK.
## Prerequisites
- Linear SDK installed and configured
- TypeScript project setup
- Understanding of async/await patterns
## Core Patterns
### Pattern 1: Client Singleton
```typescript
// lib/linear.ts
import { LinearClient } from "@linear/sdk";
let client: LinearClient | null = null;
export function getLinearClient(): LinearClient {
if (!client) {
if (!process.env.LINEAR_API_KEY) {
throw new Error("LINEAR_API_KEY environment variable not set");
}
client = new LinearClient({
apiKey: process.env.LINEAR_API_KEY,
});
}
return client;
}
```
### Pattern 2: Pagination Handling
```typescript
import { LinearClient, Issue, IssueConnection } from "@linear/sdk";
async function* getAllIssues(
client: LinearClient,
filter?: Record<string, unknown>
): AsyncGenerator<Issue> {
let hasNextPage = true;
let endCursor: string | undefined;
while (hasNextPage) {
const connection: IssueConnection = await client.issues({
filter,
first: 50, // Max per page
after: endCursor,
});
for (const issue of connection.nodes) {
yield issue;
}
hasNextPage = connection.pageInfo.hasNextPage;
endCursor = connection.pageInfo.endCursor;
}
}
// Usage
for await (const issue of getAllIssues(client, { state: { name: { eq: "Todo" } } })) {
console.log(issue.identifier, issue.title);
}
```
### Pattern 3: Error Handling Wrapper
```typescript
import { LinearClient, LinearError } from "@linear/sdk";
interface LinearResult<T> {
success: boolean;
data?: T;
error?: {
message: string;
code?: string;
retryable: boolean;
};
}
async function linearOperation<T>(
operation: () => Promise<T>
): Promise<LinearResult<T>> {
try {
const data = await operation();
return { success: true, data };
} catch (error) {
if (error instanceof LinearError) {
return {
success: false,
error: {
message: error.message,
code: error.type,
retryable: error.type === "RateLimitedError",
},
};
}
return {
success: false,
error: {
message: error instanceof Error ? error.message : "Unknown error",
retryable: false,
},
};
}
}
// Usage
const result = await linearOperation(() => client.createIssue({
teamId: team.id,
title: "New issue",
}));
if (result.success) {
console.log("Issue created:", result.data);
} else if (result.error?.retryable) {
// Implement retry logic
}
```
### Pattern 4: Batch Operations
```typescript
async function batchUpdateIssues(
client: LinearClient,
issueIds: string[],
update: { stateId?: string; priority?: number }
): Promise<{ success: number; failed: number }> {
const results = await Promise.allSettled(
issueIds.map(id => client.updateIssue(id, update))
);
return {
success: results.filter(r => r.status === "fulfilled").length,
failed: results.filter(r => r.status === "rejected").length,
};
}
```
### Pattern 5: Caching Layer
```typescript
interface CacheEntry<T> {
data: T;
expiresAt: number;
}
class LinearCache {
private cache = new Map<string, CacheEntry<unknown>>();
private ttl: number;
constructor(ttlSeconds = 60) {
this.ttl = ttlSeconds * 1000;
}
async get<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
const cached = this.cache.get(key) as CacheEntry<T> | undefined;
if (cached && cached.expiresAt > Date.now()) {
return cached.data;
}
const data = await fetcher();
this.cache.set(key, { data, expiresAt: Date.now() + this.ttl });
return data;
}
invalidate(key: string): void {
this.cache.delete(key);
}
}
// Usage
const cache = new LinearCache(300); // 5 minute TTL
const teams = await cache.get("teams", () => client.teams());
```
### Pattern 6: Type-Safe Filters
```typescript
import { IssueFilter } from "@linear/sdk";
function buildIssueFilter(options: {
teamKeys?: string[];
states?: string[];
assigneeId?: string;
priority?: number[];
}): IssueFilter {
const filter: IssueFilter = {};
if (options.teamKeys?.length) {
filter.team = { key: { in: options.teamKeys } };
}
if (options.states?.length) {
filter.state = { name: { in: options.states } };
}
if (options.assigneeId) {
filter.assignee = { id: { eq: options.assigneeId } };
}
if (options.priority?.length) {
filter.priority = { in: options.priority };
}
return filter;
}
```
## Output
- Reusable client singleton
- Pagination iterator for large datasets
- Type-safe error handling
- Efficient batch operations
- Caching for performance
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| `Type mismatch` | SDK version incompatibility | Update @linear/sdk package |
| `Undefined property` | Nullable field access | Use optional chaining (?.) |
| `Promise rejection` | Unhandled async error | Wrap in try/catch or use wrapper |
## Resources
- [Linear SDK TypeScript](https://developers.linear.app/docs/sdk/getting-started)
- [GraphQL Schema Reference](https://developers.linear.app/docs/graphql/schema)
- [TypeScript Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html)
## Next Steps
Apply these patterns in `linear-core-workflow-a` for issue management.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「linear-sdk-patterns」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次