maintainx-sdk-patterns
Learn MaintainX REST API patterns, pagination, filtering, and client architecture. Use when building robust API integrations, implementing pagination, or creating reusable SDK patterns for MaintainX. Trigger with phrases like "maintainx sdk", "maintainx api patterns", "maintainx pagination", "maintainx filtering", "maintainx client design".
What this skill does
# MaintainX SDK Patterns
## Overview
Production-grade patterns for building robust MaintainX API integrations with proper error handling, cursor-based pagination, retry logic, and type safety.
## Prerequisites
- Completed `maintainx-install-auth` setup
- TypeScript/Node.js familiarity
- Understanding of REST API principles
## Instructions
### Step 1: Type-Safe Client with Generics
```typescript
// src/maintainx/typed-client.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosError } from 'axios';
interface PaginatedResponse<T> {
cursor: string | null;
}
interface WorkOrder {
id: number;
title: string;
status: 'OPEN' | 'IN_PROGRESS' | 'ON_HOLD' | 'COMPLETED' | 'CLOSED';
priority: 'NONE' | 'LOW' | 'MEDIUM' | 'HIGH';
description?: string;
assignees: Array<{ type: 'USER' | 'TEAM'; id: number }>;
assetId?: number;
locationId?: number;
createdAt: string;
updatedAt: string;
completedAt?: string;
dueDate?: string;
categories: string[];
}
interface Asset {
id: number;
name: string;
serialNumber?: string;
model?: string;
manufacturer?: string;
locationId?: number;
createdAt: string;
}
interface WorkOrdersResponse extends PaginatedResponse<WorkOrder> {
workOrders: WorkOrder[];
}
interface AssetsResponse extends PaginatedResponse<Asset> {
assets: Asset[];
}
export class MaintainXClient {
private http: AxiosInstance;
constructor(apiKey?: string) {
const key = apiKey || process.env.MAINTAINX_API_KEY;
if (!key) throw new Error('MAINTAINX_API_KEY required');
this.http = axios.create({
baseURL: 'https://api.getmaintainx.com/v1',
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
timeout: 30_000,
});
}
async getWorkOrders(params?: Record<string, any>): Promise<WorkOrdersResponse> {
const { data } = await this.http.get<WorkOrdersResponse>('/workorders', { params });
return data;
}
async getWorkOrder(id: number): Promise<WorkOrder> {
const { data } = await this.http.get<WorkOrder>(`/workorders/${id}`);
return data;
}
async createWorkOrder(input: Partial<WorkOrder>): Promise<WorkOrder> {
const { data } = await this.http.post<WorkOrder>('/workorders', input);
return data;
}
async updateWorkOrder(id: number, input: Partial<WorkOrder>): Promise<WorkOrder> {
const { data } = await this.http.patch<WorkOrder>(`/workorders/${id}`, input);
return data;
}
async getAssets(params?: Record<string, any>): Promise<AssetsResponse> {
const { data } = await this.http.get<AssetsResponse>('/assets', { params });
return data;
}
async request<T = any>(method: string, path: string, body?: any): Promise<T> {
const config: AxiosRequestConfig = { method, url: path, data: body };
const { data } = await this.http.request<T>(config);
return data;
}
}
```
### Step 2: Cursor-Based Pagination
MaintainX uses cursor-based pagination. The response includes a `cursor` field; pass it as a query parameter to get the next page.
```typescript
async function paginate<T>(
fetcher: (cursor?: string) => Promise<{ cursor: string | null } & Record<string, T[]>>,
key: string,
): Promise<T[]> {
const all: T[] = [];
let cursor: string | undefined;
do {
const response = await fetcher(cursor);
const items = (response as any)[key] as T[];
all.push(...items);
cursor = response.cursor ?? undefined;
} while (cursor);
return all;
}
// Usage
const allWorkOrders = await paginate(
(cursor) => client.getWorkOrders({ limit: 100, cursor, status: 'OPEN' }),
'workOrders',
);
console.log(`Total open work orders: ${allWorkOrders.length}`);
const allAssets = await paginate(
(cursor) => client.getAssets({ limit: 100, cursor }),
'assets',
);
console.log(`Total assets: ${allAssets.length}`);
```
### Step 3: Retry with Exponential Backoff
```typescript
async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 3,
baseDelayMs = 1000,
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (err: any) {
const status = err?.response?.status;
const isRetryable = status === 429 || (status >= 500 && status < 600);
if (!isRetryable || attempt === maxRetries) throw err;
// Honor Retry-After header if present
const retryAfter = err.response?.headers?.['retry-after'];
const delayMs = retryAfter
? parseInt(retryAfter) * 1000
: baseDelayMs * Math.pow(2, attempt) + Math.random() * 500;
console.warn(`Retry ${attempt + 1}/${maxRetries} after ${delayMs}ms (HTTP ${status})`);
await new Promise((r) => setTimeout(r, delayMs));
}
}
throw new Error('Unreachable');
}
// Usage
const wo = await withRetry(() => client.getWorkOrder(12345));
```
### Step 4: Batch Operations
```typescript
import PQueue from 'p-queue';
const queue = new PQueue({ concurrency: 5, interval: 1000, intervalCap: 10 });
async function batchCreateWorkOrders(items: Array<Partial<WorkOrder>>): Promise<WorkOrder[]> {
const results = await Promise.all(
items.map((item) =>
queue.add(() => withRetry(() => client.createWorkOrder(item)))
),
);
return results as WorkOrder[];
}
// Create 50 PMs in controlled batches
const pms = Array.from({ length: 50 }, (_, i) => ({
title: `Weekly Inspection - Zone ${i + 1}`,
priority: 'LOW' as const,
categories: ['PREVENTIVE'],
}));
const created = await batchCreateWorkOrders(pms);
console.log(`Created ${created.length} preventive maintenance orders`);
```
### Step 5: Fluent Query Builder
```typescript
class WorkOrderQuery {
private params: Record<string, any> = {};
status(s: WorkOrder['status']) { this.params.status = s; return this; }
priority(p: WorkOrder['priority']) { this.params.priority = p; return this; }
assignee(userId: number) { this.params.assigneeId = userId; return this; }
asset(assetId: number) { this.params.assetId = assetId; return this; }
location(locationId: number) { this.params.locationId = locationId; return this; }
createdAfter(date: string) { this.params.createdAtGte = date; return this; }
createdBefore(date: string) { this.params.createdAtLte = date; return this; }
limit(n: number) { this.params.limit = n; return this; }
async execute(client: MaintainXClient) {
return client.getWorkOrders(this.params);
}
}
// Usage
const results = await new WorkOrderQuery()
.status('OPEN')
.priority('HIGH')
.location(2345)
.createdAfter('2026-01-01T00:00:00Z')
.limit(25)
.execute(client);
```
## Output
- Type-safe MaintainX client with full TypeScript interfaces
- Cursor-based pagination utility that works across all list endpoints
- Retry logic with exponential backoff and `Retry-After` header support
- Rate-limited batch processor using `p-queue`
- Fluent query builder for readable work order filters
## Error Handling
| Pattern | Use Case |
|---------|----------|
| `withRetry()` | Transient errors (429, 5xx) with exponential backoff |
| `paginate()` | Collecting all items from cursor-based endpoints |
| `PQueue` | Controlled concurrency to avoid rate limits |
| `WorkOrderQuery` | Type-safe filtering to prevent invalid API calls |
## Resources
- MaintainX API Reference
- [p-queue](https://github.com/sindresorhus/p-queue) -- Promise queue with concurrency control
## Next Steps
For core workflows, see `maintainx-core-workflow-a` (Work Orders) and `maintainx-core-workflow-b` (Assets).
## Examples
**Stream large datasets with async iterators**:
```typescript
async function* streamWorkOrders(client: MaintainXClient, params?: Record<string, any>) {
let cursor: string | undefined;
do {
const response = await client.getWorkOrders({ ...params, limit: 100, cursor });
for (const wo of response.workOrders) {
yield wo;
}
cursor = response.cursor ?? undefined;
} while (cursor);
}
for await (const wo of streamWorkOrders(client, { status: 'COMPLETRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.