설치
Copy
npm install @sajuapi/sdk
빠른 시작
Copy
import { SajuClient, SajuCalculator } from '@sajuapi/sdk';
// 클라이언트 초기화
const client = new SajuClient({
apiKey: process.env.SAJU_API_KEY
});
// 사주 계산 (로컬 실행, API 호출 없음)
const saju = SajuCalculator.calculate({
year: 1990,
month: 5,
day: 15,
hour: 14,
gender: 'male'
});
// 일일 운세 조회
const fortune = await client.getDailyFortune({
saju,
userName: '홍길동',
model: 'haiku'
});
console.log(fortune.todayFortune.score); // 78
설정
Copy
const client = new SajuClient({
// 필수
apiKey: 'bs_live_xxx',
// 선택
baseUrl: 'https://api.sajuapi.dev', // 커스텀 API URL
timeout: 30000, // 요청 타임아웃 (ms)
retries: 3, // 실패 시 자동 재시도
debug: false // 디버그 로깅 활성화
});
SajuCalculator
API 호출 없이 로컬에서 사주팔자 계산:Copy
import { SajuCalculator } from '@sajuapi/sdk';
const saju = SajuCalculator.calculate({
year: 1990,
month: 5,
day: 15,
hour: 14, // 24시간 형식, 모르면 null
minute: 30, // 선택
gender: 'male',
calendarType: 'solar' // 'solar' 또는 'lunar'
});
// 사주 접근
console.log(saju.pillars.day.stem.hangul); // "병"
console.log(saju.dayMaster.element); // "fire"
console.log(saju.elementBalance.weakest); // "water"
API 메서드
getDailyFortune
전체 일일 운세 조회:Copy
const fortune = await client.getDailyFortune({
saju: saju,
userName: '홍길동',
model: 'haiku', // 'haiku' | 'sonnet' | 'gpt4o'
date: '2024-01-15', // 선택, 기본값 오늘
type: 'all' // 'all' | 'fortune_only' | 'character'
});
// 응답 타입
interface FortuneResponse {
character: {
dayMaster: string;
emoji: string;
identity: string;
investmentIdentity: string;
};
investmentTendency: {
scores: {
riskTolerance: number;
longTermAptitude: number;
trendSensitivity: number;
};
summary: string;
};
todayFortune: {
score: number;
overallAnalysis: string;
actionItems: Array<{ type: 'do' | 'avoid'; text: string }>;
timing: {
best: string;
avoid: string;
reason: string;
};
};
whyExplanation: string;
}
streamDailyFortune
점진적 업데이트와 함께 운세 스트리밍:Copy
const stream = client.streamDailyFortune({
saju,
userName: '홍길동'
});
stream.on('character', (data) => {
console.log('성격 로드됨:', data.dayMaster);
});
stream.on('tendency', (data) => {
console.log('성향 로드됨:', data.scores);
});
stream.on('fortune', (data) => {
console.log('운세 로드됨:', data.score);
});
stream.on('complete', () => {
console.log('모든 데이터 로드됨');
});
stream.on('error', (error) => {
console.error('스트림 에러:', error);
});
// 또는 async iterator 사용
for await (const event of stream) {
console.log(event.type, event.data);
}
getUsage
API 사용량 확인:Copy
const usage = await client.getUsage();
console.log(usage.today.requests); // 847
console.log(usage.today.cost); // 11.01
console.log(usage.thisMonth.cost); // 200.46
React Hooks
Copy
import { useSaju, useFortune } from '@sajuapi/sdk/react';
function FortuneComponent() {
// 사용자 데이터로 사주 계산
const { saju, isCalculating } = useSaju({
year: 1990,
month: 5,
day: 15,
hour: 14,
gender: 'male'
});
// 운세 조회
const { fortune, isLoading, error, refetch } = useFortune({
saju,
userName: '홍길동',
enabled: !!saju // 사주가 준비되면 조회
});
if (isLoading) return <Spinner />;
if (error) return <Error message={error.message} />;
return (
<div>
<h1>오늘의 투자운: {fortune.todayFortune.score}점</h1>
<p>{fortune.todayFortune.overallAnalysis}</p>
</div>
);
}
에러 처리
Copy
import { SajuClientError } from '@sajuapi/sdk';
try {
const fortune = await client.getDailyFortune({ saju, userName });
} catch (error) {
if (error instanceof SajuClientError) {
switch (error.code) {
case 'rate_limited':
// 대기 후 재시도
await sleep(error.retryAfter * 1000);
break;
case 'invalid_api_key':
// 인증 에러 처리
break;
default:
console.error(`에러 ${error.code}: ${error.message}`);
}
}
}
TypeScript 타입
전체 TypeScript 지원 및 타입 내보내기:Copy
import type {
Saju,
Pillar,
FortuneResponse,
CharacterData,
TodayFortune,
ActionItem,
ModelType
} from '@sajuapi/sdk';
브라우저 사용
브라우저 환경에서는 UMD 빌드 사용:Copy
<script src="https://unpkg.com/@sajuapi/sdk/dist/browser.min.js"></script>
<script>
const client = new SajuClient.Client({ apiKey: 'bs_live_xxx' });
const saju = SajuClient.SajuCalculator.calculate({ ... });
</script>
API 키를 클라이언트 코드에 절대 노출하지 마세요. 프로덕션에서는 백엔드 프록시를 사용하세요.
Next.js 통합
Copy
// app/api/fortune/route.ts
import { SajuClient } from '@sajuapi/sdk';
const client = new SajuClient({
apiKey: process.env.SAJU_API_KEY
});
export async function POST(request: Request) {
const { saju, userName } = await request.json();
const fortune = await client.getDailyFortune({ saju, userName });
return Response.json(fortune);
}