AppFolio SDK 模式
概述
适用于 AppFolio 物业管理 REST API 的生产级模式。AppFolio 使用带有客户端凭证的 HTTP 基本认证,并以 JSON 格式返回属性、租户、租约和工单数据。一个结构化的单例客户端能够防止凭据泄露、强制执行一致的错误处理,并集中管理所有物业管理端点的分页逻辑。
前置条件
- 提供者已验证的基础 URL、认证方法、端点范围以及目标投资组合的托管密钥注入路径。
- 所有支持变更的服务方法需具备模式验证、请求超时、端点特定的速率限制和幂等键。
- 用于单元测试的合成固件;生产环境的租户、租约和支付负载不得成为默认的模拟、日志或错误消息内容。
操作说明
- 每个运行时构建一个受契约约束的客户端,并在请求开始前拒绝缺失或无效的配置。
- 在服务边界验证查询范围和响应形状,然后仅向调用者传递最小化的类型化字段。
- 向调用者返回分类的
429或未知写入失败;仅在调用者记录游标/键和延迟后,重试幂等操作。 - 将写入工作流保持在显式授权、审计和对账控制之后,而不是将其嵌入通用的 SDK 便捷帮助程序中。
单例客户端
import axios, { AxiosInstance } from 'axios';
let _client: AxiosInstance | null = null;
export function getClient(): AxiosInstance {
if (!_client) {
const clientId = process.env.APPFOLIO_CLIENT_ID;
const clientSecret = process.env.APPFOLIO_CLIENT_SECRET;
const baseURL = process.env.APPFOLIO_BASE_URL;
if (!clientId || !clientSecret || !baseURL) throw new Error('需要 APPFOLIO_CLIENT_ID、SECRET 和 BASE_URL');
_client = axios.create({ baseURL, auth: { username: clientId, password: clientSecret }, timeout: 30000 });
}
return _client;
}
错误封装
export class AppFolioError extends Error {
constructor(public status: number, public code: string, message: string) { super(message); }
}
export async function safeCall<T>(operation: string, fn: () => Promise<T>): Promise<T> {
try { return await fn(); }
catch (err: any) {
const status = err.response?.status ?? 0;
if (status === 429) {
const retryAfter = err.response?.headers?.['retry-after'];
throw new AppFolioError(429, 'RATE_LIMIT', `在 ${retryAfter ?? '提供者指定的延迟'} 后重试;不要自动重放未知写入`);
}
if (status === 401) throw new AppFolioError(401, 'AUTH', '无效的 APPFOLIO_CLIENT_ID 或 SECRET');
throw new AppFolioError(status, 'API_ERROR', `${operation} 失败 [${status}]: ${err.message}`);
}
}
请求构建器
class AppFolioQuery {
private params: Record<string, string> = {};
status(s: 'active' | 'past' | 'future') { this.params.status = s; return this; }
propertyId(id: string) { this.params.property_id = id; return this; }
page(n: number) { this.params.page = String(n); return this; }
perPage(n: number) { this.params.per_page = String(Math.min(n, 200)); return this; }
since(date: string) { this.params.updated_since = date; return this; }
build() { return this.params; }
}
// 用法: new AppFolioQuery().status('active').perPage(50).build();
响应类型
interface Property {
id: string; name: string; property_type: 'residential' | 'commercial' | 'mixed';
address: { street: string; city: string; state: string; zip: string };
unit_count: number; status: string;
}
interface Tenant {
id: string; first_name: string; last_name: string;
email: string; phone: string; unit_id: string; lease_id: string;
}
interface Lease {
id: string; unit_id: string; tenant_id: string;
start_date: string; end_date: string; rent_amount: number; status: 'active' | 'expired' | 'future';
}
interface WorkOrder {
id: string; property_id: string; unit_id: string;
description: string; priority: 'low' | 'medium' | 'high' | 'emergency';
status: 'open' | 'in_progress' | 'completed';
}
测试工具
export function mockProperty(overrides: Partial<Property> = {}): Property {
return { id: 'prop-001', name: 'Maple Ridge Apts', property_type: 'residential',
address: { street: '100 Main St', city: 'Austin', state: 'TX', zip: '78701' },
unit_count: 24, status: 'active', ...overrides };
}
export function mockLease(overrides: Partial<Lease> = {}): Lease {
return { id: 'lease-001', unit_id: 'unit-001', tenant_id: 'ten-001',
start_date: '2025-01-01', end_date: '2026-01-01', rent_amount: 1500, status: 'active', ...overrides };
}
错误处理
| 模式 | 使用时机 | 示例 |
|---|---|---|
safeCall 封装 | 所有 API 调用 | 防止未捕获的 4xx/5xx 导致流程崩溃 |
| 调用者拥有的 429 重试 | 受速率限制的幂等批量读取 | 保留游标/键,遵循 Retry-After,然后谨慎重试 |
| 身份验证验证 | 客户端初始化 | 凭据缺失时尽早抛出错误 |
| 分页循环 | 列出属性/租户 | 增加 page 直到响应为空 |
输出
- 一个经过验证、受契约约束的 API 客户端,具有集中的超时和错误分类行为
- 受限的查询参数和最小化的类型化响应,供服务调用者使用
- 显式的速率限制和未知写入结果,要求调用者做出游标/幂等性/对账决策
示例
对于属性列表读取,构建一个具有封顶页面大小的查询,通过 safeCall 执行,并对照合成固件验证返回的属性 ID 和计数。对于变更操作,在分派前持久化一个幂等键,并将超时或 429 视为暂停/对账条件,而不是再次调用该函数。如果客户端配置、响应模式或写入结果未经验证,则停止工作流并向所有者呈现一个脱敏的错误。
资源
后续步骤
在 appfolio-core-workflow-a 中应用这些模式。