salesforce-sdk-patterns
Apply production-ready Salesforce jsforce patterns for TypeScript and Python. Use when implementing Salesforce integrations, refactoring SDK usage, or establishing team coding standards for Salesforce. Trigger with phrases like "salesforce SDK patterns", "jsforce best practices", "salesforce code patterns", "idiomatic salesforce", "salesforce typescript".
What this skill does
# Salesforce SDK Patterns
## Overview
Production-ready patterns for jsforce (Node.js) and simple-salesforce (Python) — singleton connections, typed queries, error handling, and token refresh.
## Prerequisites
- Completed `salesforce-install-auth` setup
- Familiarity with async/await and TypeScript generics
- Understanding of Salesforce sObject model
## Instructions
### Step 1: Singleton Connection with Auto-Refresh
```typescript
// src/salesforce/connection.ts
import jsforce from 'jsforce';
let conn: jsforce.Connection | null = null;
export async function getConnection(): Promise<jsforce.Connection> {
if (conn?.accessToken) {
// Test if token is still valid
try {
await conn.identity();
return conn;
} catch {
conn = null; // Token expired, reconnect
}
}
conn = new jsforce.Connection({
loginUrl: process.env.SF_LOGIN_URL || 'https://login.salesforce.com',
version: '59.0', // Pin API version for stability
});
await conn.login(
process.env.SF_USERNAME!,
process.env.SF_PASSWORD! + process.env.SF_SECURITY_TOKEN!
);
return conn;
}
```
### Step 2: Typed sObject Interfaces
```typescript
// src/salesforce/types.ts
/** Standard Salesforce sObject base fields */
interface SObjectBase {
Id: string;
CreatedDate: string;
LastModifiedDate: string;
SystemModstamp: string;
IsDeleted: boolean;
}
export interface Account extends SObjectBase {
Name: string;
Industry?: string;
AnnualRevenue?: number;
NumberOfEmployees?: number;
Website?: string;
Phone?: string;
BillingCity?: string;
BillingState?: string;
OwnerId: string;
}
export interface Contact extends SObjectBase {
FirstName?: string;
LastName: string;
Email?: string;
Phone?: string;
AccountId?: string;
Title?: string;
Department?: string;
}
export interface Opportunity extends SObjectBase {
Name: string;
Amount?: number;
StageName: string;
CloseDate: string;
AccountId?: string;
Probability?: number;
ForecastCategory?: string;
}
export interface Lead extends SObjectBase {
FirstName?: string;
LastName: string;
Company: string;
Email?: string;
Status: string;
IsConverted: boolean;
}
```
### Step 3: Type-Safe Query Builder
```typescript
// src/salesforce/queries.ts
import { getConnection } from './connection';
import type { Account, Contact, Opportunity } from './types';
export async function queryAccounts(
filters?: { industry?: string; minRevenue?: number }
): Promise<Account[]> {
const conn = await getConnection();
let soql = `
SELECT Id, Name, Industry, AnnualRevenue, NumberOfEmployees,
Website, Phone, BillingCity, BillingState, OwnerId
FROM Account
`;
const conditions: string[] = [];
if (filters?.industry) {
conditions.push(`Industry = '${filters.industry.replace(/'/g, "\\'")}'`);
}
if (filters?.minRevenue) {
conditions.push(`AnnualRevenue >= ${filters.minRevenue}`);
}
if (conditions.length > 0) {
soql += ` WHERE ${conditions.join(' AND ')}`;
}
soql += ' ORDER BY Name ASC LIMIT 200';
const result = await conn.query<Account>(soql);
return result.records;
}
export async function queryContactsByAccount(
accountId: string
): Promise<Contact[]> {
const conn = await getConnection();
const result = await conn.query<Contact>(
`SELECT Id, FirstName, LastName, Email, Phone, Title, Department
FROM Contact
WHERE AccountId = '${accountId}'
ORDER BY LastName ASC`
);
return result.records;
}
export async function queryOpenOpportunities(): Promise<Opportunity[]> {
const conn = await getConnection();
const result = await conn.query<Opportunity>(
`SELECT Id, Name, Amount, StageName, CloseDate, AccountId, Probability
FROM Opportunity
WHERE IsClosed = false AND CloseDate >= TODAY
ORDER BY CloseDate ASC`
);
return result.records;
}
```
### Step 4: Error Handling Wrapper
```typescript
// src/salesforce/errors.ts
export class SalesforceError extends Error {
constructor(
message: string,
public readonly errorCode: string,
public readonly statusCode?: number,
public readonly fields?: string[]
) {
super(message);
this.name = 'SalesforceError';
}
}
export async function safeSfCall<T>(
operation: () => Promise<T>,
context?: string
): Promise<T> {
try {
return await operation();
} catch (err: any) {
const errorCode = err.errorCode || err.name || 'UNKNOWN_ERROR';
const fields = err.fields || [];
// Map Salesforce error codes to actionable messages
const messages: Record<string, string> = {
'INVALID_FIELD': `Invalid field name in query. Fields: ${fields.join(', ')}`,
'MALFORMED_QUERY': 'SOQL syntax error — check field names and WHERE clause',
'INVALID_TYPE': 'sObject type does not exist — use API names like Account, not Accounts',
'INSUFFICIENT_ACCESS_OR_READONLY': 'User lacks permission for this operation',
'ENTITY_IS_DELETED': 'Record has been deleted — check Recycle Bin',
'DUPLICATE_VALUE': 'Duplicate external ID or unique field value',
'FIELD_INTEGRITY_EXCEPTION': 'Field validation rule failed',
'STRING_TOO_LONG': 'Field value exceeds max length',
'REQUEST_LIMIT_EXCEEDED': 'Daily API limit exhausted — check org limits',
};
throw new SalesforceError(
messages[errorCode] || err.message || 'Unknown Salesforce error',
errorCode,
err.statusCode,
fields
);
}
}
```
### Step 5: Retry Logic for Transient Errors
```typescript
const RETRYABLE_ERRORS = [
'REQUEST_LIMIT_EXCEEDED',
'SERVER_UNAVAILABLE',
'UNABLE_TO_LOCK_ROW',
];
export async function withRetry<T>(
operation: () => Promise<T>,
maxRetries = 3,
baseDelayMs = 1000
): Promise<T> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (err: any) {
const errorCode = err.errorCode || err.name;
if (attempt === maxRetries || !RETRYABLE_ERRORS.includes(errorCode)) {
throw err;
}
const delay = baseDelayMs * Math.pow(2, attempt - 1);
console.warn(`Retryable error ${errorCode}, attempt ${attempt}/${maxRetries}, waiting ${delay}ms`);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}
```
## Output
- Type-safe jsforce connection singleton with auto-refresh
- Typed sObject interfaces for Account, Contact, Opportunity, Lead
- SOQL query builders with parameterized filters
- Error handling mapped to Salesforce error codes
- Retry logic for transient failures
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| `safeSfCall()` wrapper | All API calls | Maps error codes to human messages |
| `withRetry()` | Transient failures (`UNABLE_TO_LOCK_ROW`) | Automatic recovery |
| Typed queries | All SOQL | Catches field mismatches at compile time |
| Token refresh | Long-running processes | Prevents session expiration |
## Resources
- [jsforce API Reference](https://jsforce.github.io/document/)
- [Salesforce Error Codes](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_concepts_core_data_objects.htm)
- [SOQL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql.htm)
## Next Steps
Apply patterns in `salesforce-core-workflow-a` for CRUD operations at scale.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.