sim-request
v0.1.3
Published
Flexible request library with proxy, security, interceptors, and custom response types.
Readme
📦 sim-request
간단하고 가벼운 HTTP 클라이언트 라이브러리입니다.
브라우저/React 환경에서 fetch를 감싸 더 편리하게 사용할 수 있도록 설계되었습니다.
Axios 스타일의 API, 인터셉터, 자동 JSON 변환, 파일 업로드/다운로드, 중복 방지 등 다양한 기능을 제공합니다.
✨ 주요 기능
GET,POST,PUT,PATCH,DELETE헬퍼 메서드 제공- 요청/응답/에러 인터셉터
timeout,credentials,mode(cors/no-cors/same-origin)지원transform/map으로 응답 데이터 후처리- 자동 캐시 무효화 (
_tsquery param) - 중복 요청 방지 (in-flight deduplication)
- 파일 업로드 (
FormData) - 파일 다운로드 (
Blob, 자동 저장 지원)
📦 설치
npm install sim-request
🚀 사용법
1. 인스턴스 생성
ts
복사
편집
import { simpleRequest } from "sim-request";
const api = simpleRequest({
baseURL: "http://localhost:8080",
timeout: 10000,
mode: "cors",
});
2. 기본 요청
ts
복사
편집
// GET
const res = await api.get("/users", { params: { page: 1 } });
console.log(res.data);
// POST
await api.post("/users", { name: "Alice" });
3. 인터셉터
ts
복사
편집
// 요청 인터셉터
api.useRequest(async (req) => {
console.log("➡️ Request:", req.url);
return req;
});
// 응답 인터셉터
api.useResponse(async (res) => {
console.log("✅ Response:", res.status);
return res;
});
// 에러 인터셉터
api.useError(async (err) => {
console.error("❌ Error:", err);
return err;
});
4. transform / map
ts
복사
편집
// transform: 응답 데이터 후처리
const res = await api.get("/profile", {
transform: (raw) => raw.user,
});
// map: 필드 매핑
const res2 = await api.get("/profile", {
map: { id: "user_id", name: "user_name" },
});
5. 중복 요청 방지
동일한 URL + Method + Params/Data 조합의 요청이 동시에 발생하면 하나만 네트워크 요청하고, 나머지는 결과를 공유합니다.
ts
복사
편집
const [a, b] = await Promise.all([
api.get("/users"),
api.get("/users"),
]);
console.log(a === b); // ✅ true
6. 파일 업로드
ts
복사
편집
const form = new FormData();
form.append("file", fileInput.files[0]);
await api.post("/upload", form);
7. 파일 다운로드
ts
복사
편집
// 자동 저장
await api.download("/report.pdf", { filename: "my-report.pdf" });
// Blob 직접 사용
const blob = await api.download("/report.pdf");
console.log(blob);
⚙️ React Proxy 설정 예시
React 앱에서 Spring Boot 백엔드와 함께 사용할 경우, CORS 대신 프록시를 설정할 수 있습니다.
package.json
json
복사
편집
{
"proxy": "http://localhost:8080"
}
이제 프론트에서 fetch("/api/xxx") 요청 시 자동으로 백엔드로 프록시됩니다.
📖 API
Instance
ts
복사
편집
const api = simpleRequest(config?: SimpleRequestConfig);
Config
ts
복사
편집
export interface SimpleRequestConfig {
baseURL?: string;
headers?: Record<string, string>;
timeout?: number;
credentials?: RequestCredentials;
responseType?: "json" | "text" | "auto" | "blob";
mode?: RequestMode; // "cors" | "no-cors" | "same-origin"
noCache?: boolean; // 캐시 무효화 (기본 true)
}
Methods
request(opts)
get(url, opts)
post(url, data, opts)
put(url, data, opts)
patch(url, data, opts)
delete(url, opts)
download(url, opts) → Blob 반환 또는 자동 저장
Interceptors
useRequest(fn)
useResponse(fn)
useError(fn)
🛠️ 개발 계획
기본 요청
인터셉터
캐시 무효화
transform / map
중복 요청 방지
업로드/다운로드
재시도 / backoff
요청 취소(cancel token)
Node.js 환경 지원
