AppFolio SDK 패턴
개요
AppFolio 부동산 관리 REST API를 위한 프로덕션 준비 패턴입니다. AppFolio는 HTTP Basic Auth와 클라이언트 자격 증명을 사용하며, 부동산, 세입자, 임대료, 작업 지시에 대해 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, and BASE_URL required');
_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', `Retry after ${retryAfter ?? 'provider-directed delay'}; do not replay an unknown write automatically`);
}
if (status === 401) throw new AppFolioError(401, 'AUTH', 'Invalid APPFOLIO_CLIENT_ID or SECRET');
throw new AppFolioError(status, 'API_ERROR', `${operation} failed [${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; }
}
// Usage: 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에 패턴을 적용합니다.