Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion .workspace/github.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
{
"description": "Generates and keeps in sync the TanStack Query v5 layer (query keys, queryOptions, infiniteQueryOptions, mutationOptions) from your existing TypeScript API functions. No OpenAPI spec needed; your API code stays as it is. Includes watch mode and a CI check."
"description": "TanStack Query codegen without OpenAPI: generates query keys and queryOptions, infiniteQueryOptions and mutationOptions from your existing TypeScript API functions. Try it in the browser playground; watch mode and a CI check included.",
"homepage": "https://react-query-helper.vercel.app/en/",
"topics": [
"react-query",
"tanstack-query",
"codegen",
"code-generator",
"typescript",
"query-key-factory",
"queryoptions",
"openapi-alternative",
"react",
"cli"
]
}
10 changes: 5 additions & 5 deletions .workspace/showcase.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
"symbol": "⇄",
"color": "#c0cfa5",
"summary": "웹 앱이 서버 데이터를 불러오는 연결 코드를 자동으로 만들어 주는 개발 도구",
"description": "React 웹 앱이 서버에서 데이터를 불러오고 저장할 때 필요한 연결 코드를 자동으로 만들어 주는 개발 도구입니다. 이미 작성해 둔 TypeScript API 함수를 읽어 TanStack Query v5에서 쓰는 쿼리 키와 옵션 코드를 생성합니다. 기존 API 코드와 인증, 에러 처리는 그대로 두고, OpenAPI 명세가 없어도 동작합니다. API 함수가 바뀌면 다시 생성해 맞추고, CI에서 생성 파일이 오래됐는지 검사할 수 있습니다. 데모 사이트에서 예제 함수와 실제 생성 결과를 나란히 볼 수 있습니다.",
"description": "React 웹 앱이 서버에서 데이터를 불러오고 저장할 때 필요한 연결 코드를 자동으로 만들어 주는 개발 도구입니다. 이미 작성해 둔 TypeScript API 함수를 읽어 TanStack Query v5에서 쓰는 쿼리 키와 옵션 코드를 생성합니다. 기존 API 코드와 인증, 에러 처리는 그대로 두고, OpenAPI 명세가 없어도 동작합니다. API 함수가 바뀌면 다시 생성해 맞추고, CI에서 생성 파일이 오래됐는지 검사할 수 있습니다. 설치하기 전에 데모 사이트에 함수를 붙여 넣어 생성 결과를 바로 볼 수 있습니다.",
"features": [
"기존 TypeScript API 함수에서 쿼리 키와 옵션 코드 생성",
"함수 이름에 따라 조회용과 변경용 코드를 나눠 생성",
"인자와 반환값 타입을 원본 함수에서 그대로 추론",
"API 함수가 바뀌면 다시 생성하는 watch 모드",
"CI에서 오래된 생성 파일을 찾아내는 검사 명령",
"생성 규칙과 템플릿을 프로젝트에 맞게 변경",
"데모에서 원본 함수와 생성 결과 비교"
"설치 없이 브라우저에서 함수를 붙여 넣고 결과 확인"
],
"status": "live",
"page": {
Expand All @@ -38,7 +38,7 @@
"storyTitle": "누구나 반복하던 연결 코드를 자동으로",
"story": [
"React Query를 도입하면 API 함수에 연결된 쿼리 키와 옵션 함수를 거의 같은 모양으로 계속 만들게 됩니다. 팀이 바뀌어도 형태는 비슷했고, 그래서 사람이 쓸 필요가 없다고 판단했습니다.",
"기존 TypeScript API 함수를 읽어 TanStack Query v5의 쿼리 키와 옵션 코드를 만듭니다. 기존 API 코드와 인증, 에러 처리는 그대로 둡니다. 데모에서 원본 함수와 생성 결과를 나란히 볼 수 있습니다.",
"기존 TypeScript API 함수를 읽어 TanStack Query v5의 쿼리 키와 옵션 코드를 만듭니다. 기존 API 코드와 인증, 에러 처리는 그대로 둡니다. 데모 사이트에서는 패키지의 실제 생성기가 브라우저에서 돌아서, 함수를 붙여 넣으면 명령어가 쓸 파일과 같은 결과가 바로 나옵니다.",
"API가 바뀌었는데 생성 결과는 이전 상태로 남는 경우도 다뤘습니다. watch 모드로 다시 생성하고, CI에서 생성 파일이 오래됐는지 검사할 수 있습니다.",
"OpenAPI 명세가 있다면 Orval, Kubb, Hey API처럼 명세에서 바로 생성하는 도구가 더 맞을 수 있습니다. 이 도구는 명세 없이 TypeScript 함수만 있는 경우를 위한 것입니다."
],
Expand All @@ -59,7 +59,7 @@
}
],
"evidence": {
"verifiedAt": "2026-12-02",
"note": "2026-12-02 npm 최신 2.0.4(2026-11-26 게시) 확인. 데모 사이트와 GitHub 저장소 HTTP 200, 데모에 실제 생성기로 만든 getUser/createUser/listPosts 원본과 생성 결과가 나옴. README '지금 되는 것'(generate, generate --check, watch, artifactsByName, 커스텀 분석기·템플릿) 기준으로 기능 작성."
"verifiedAt": "2026-12-05",
"note": "2026-12-05 데모 사이트에 브라우저 플레이그라운드 추가(실제 analyzer·generator·prettier를 번들). 같은 입력으로 CLI generate 결과와 플레이그라운드 출력이 일치함을 확인. npm 최신 2.0.4, 주간 다운로드 471(2026-11-27~12-03)."
}
}
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 2.1.0

- Add `analyzeSource(fileName, text, config)` to `@uiwwsw/react-query-helper/core/analyzer`, which analyzes source text without reading a file. `analyzeFile` keeps its behavior.
- The demo site has a playground: paste API functions and see the generated keys and options, produced by the same analyzer, generator and Prettier formatting as `generate`.
- The npm page shows the English README; the Korean README moved to `README.ko.md`.

## 2.0.4

- README and package description position the tool as a generator of the TanStack Query layer from existing API functions, with fit and roadmap sections. No code changes.
Expand Down
171 changes: 171 additions & 0 deletions README.ko.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/uiwwsw/react-query-helper/main/assets/readme-hero-dark.svg" />
<img src="https://raw.githubusercontent.com/uiwwsw/react-query-helper/main/assets/readme-hero.svg" alt="React Query Helper logo" width="1120" />
</picture>
</p>

<h1 align="center">React Query Helper</h1>

<p align="center">
기존 TypeScript API 함수는 그대로 두고, 그 위의 TanStack Query 계층(쿼리 키·옵션)을 생성하고 동기화하는 코드 생성 도구
</p>

<p align="center">
<a href="https://www.npmjs.com/package/@uiwwsw/react-query-helper"><img src="https://img.shields.io/npm/v/@uiwwsw/react-query-helper?style=flat-square" alt="npm 버전" /></a>
<a href="https://github.com/uiwwsw/react-query-helper/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@uiwwsw/react-query-helper?style=flat-square" alt="라이선스" /></a>
<a href="https://github.com/uiwwsw/react-query-helper/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/uiwwsw/react-query-helper/ci.yml?branch=main&amp;style=flat-square&amp;label=CI" alt="main 브랜치 CI 상태" /></a>
<a href="https://tanstack.com/query"><img src="https://img.shields.io/npm/dependency-version/@uiwwsw/react-query-helper/peer/@tanstack/react-query?style=flat-square&amp;label=TanStack%20Query" alt="TanStack Query peer 의존성 범위" /></a>
<a href="https://www.npmjs.com/package/@uiwwsw/react-query-helper"><img src="https://img.shields.io/node/v/@uiwwsw/react-query-helper?style=flat-square" alt="Node.js 요구 버전" /></a>
<a href="https://www.npmjs.com/package/@uiwwsw/react-query-helper"><img src="https://img.shields.io/npm/types/@uiwwsw/react-query-helper?style=flat-square" alt="포함된 TypeScript 타입" /></a>
</p>

<p align="center">
<a href="https://react-query-helper.vercel.app/#demo">플레이그라운드</a> ·
<a href="https://github.com/uiwwsw/react-query-helper/blob/main/docs/ARCHITECTURE.md">구성과 의존성</a> ·
<a href="https://www.npmjs.com/package/@uiwwsw/react-query-helper">npm</a> ·
<a href="https://github.com/uiwwsw/react-query-helper/blob/main/CHANGELOG.md">변경 이력</a> ·
<a href="https://github.com/uiwwsw/react-query-helper/blob/main/README.md">English</a>
</p>

**OpenAPI 없이, 기존 API는 그대로, Query 계층은 자동으로.** 이미 쓰고 있는 TypeScript API 함수에서 쿼리 키와 TanStack Query v5 옵션 팩토리(`queryOptions`, `infiniteQueryOptions`, `mutationOptions`)를 생성하고, API가 바뀌면 다시 맞춥니다.

<p align="center">
<a href="https://react-query-helper.vercel.app/#demo"><img src="https://raw.githubusercontent.com/uiwwsw/react-query-helper/main/assets/playground.gif" alt="왼쪽 플레이그라운드에 API 함수를 입력하면 오른쪽에 생성된 쿼리 키와 옵션 팩토리가 바로 바뀌는 화면" width="960" /></a>
</p>

**[브라우저에서 바로 써 보기 →](https://react-query-helper.vercel.app/#demo)** API 함수를 붙여 넣으면 생성될 키와 옵션이 나옵니다. 설치할 것은 없습니다.

> **버전 안내:** 이 문서는 **2.x** 기준입니다. 실제 게시 버전은 위 npm 배지에서 확인하세요. 1.x를 사용 중이라면 [1.3.0 문서](https://github.com/uiwwsw/react-query-helper/blob/v1.3.0/README.md)와 [마이그레이션 가이드](https://github.com/uiwwsw/react-query-helper/blob/main/docs/REFERENCE.md#1x에서-이전)를 참고하세요. 아직 게시되지 않은 변경은 [소스에서 설치](https://github.com/uiwwsw/react-query-helper/blob/main/docs/REFERENCE.md#npm-게시-전-소스에서-설치하기)할 수 있습니다.

## 왜 필요한가

TanStack Query는 `queryOptions`로 쿼리 키와 조회 함수를 묶어 재사용하는 방식을 공식으로 제공합니다. 다만 그 연결은 API 함수마다 사람이 직접 써야 합니다.

```ts
export const userOptions = (id: string) =>
queryOptions({ queryKey: ["users", id], queryFn: () => getUser(id) });
```

API 함수가 수백 개가 되고 여러 사람이 함께 관리하면, 키 이름 규칙, 함수와 옵션의 연결, 인자가 바뀔 때의 동기화가 매번 반복되는 일이 됩니다. React Query Helper는 이 연결을 생성기로 고정합니다. 캐싱, 재시도, 데이터 요청은 지금처럼 TanStack Query가 하고, 이 도구는 그 앞의 연결 코드만 만듭니다.

## 다른 도구와 다른 점

- **기존 API 계층을 그대로 씁니다.** 생성 파일은 `outputDir`에 따로 만들어지고 원본 API 함수를 import만 합니다. 인증 헤더, 인터셉터, 에러 처리, 응답 변환을 넣어 둔 기존 `fetch`·axios 래퍼와 비즈니스 로직이 그대로 남습니다. [Orval](https://orval.dev), [Kubb](https://kubb.dev), [Hey API](https://heyapi.dev)는 OpenAPI 명세에서 API 함수 자체를 생성하므로, 손으로 쓴 API 함수가 생성된 함수로 대체됩니다(fetch 인스턴스는 직접 지정할 수 있습니다).
- **명세 없이 동작합니다.** 입력은 이미 있는 TypeScript 함수입니다. OpenAPI·Swagger 명세가 없거나 최신이 아닌 프로젝트에서도 씁니다.
- **키 규칙이 자동으로 통일됩니다.** `libs/users/api.ts`의 `getUser`는 `["users", "api", "getUser"]`가 됩니다. 사람마다 다른 키 이름을 쓰는 문제가 없습니다. [`@lukemorales/query-key-factory`](https://github.com/lukemorales/query-key-factory)는 키 구조를 직접 선언해야 하고, 이 도구는 옵션 팩토리까지 생성합니다.
- **타입을 다시 선언하지 않습니다.** 인자, 반환값, `select` 결과 타입이 원본 함수에서 추론됩니다.
- **생성물은 평범한 TypeScript 파일입니다.** 런타임에 API를 탐색하지 않고 실제 `.ts` 파일을 만들기 때문에, 코드 리뷰에서 보이고 IDE에서 정의로 따라갈 수 있습니다. 별도의 캐시나 쿼리 엔진도 없습니다.
- **API와 Query 계층이 어긋나지 않습니다.** `watch`가 API 변경을 감지해 다시 생성하고, `generate --check`가 CI에서 오래된 생성 파일을 잡아냅니다.
- **규칙을 프로젝트에 맞출 수 있습니다.** 함수별 생성 종류(`artifactsByName`), 분석기(`customAnalyzerPath`), 템플릿(`customTemplatePath`)을 바꿀 수 있습니다.

## 이런 프로젝트에 맞습니다

- 인증·에러 처리가 들어간 `fetch`·axios API 계층이 이미 있는 프로젝트
- 백엔드가 OpenAPI 명세를 제공하지 않거나 명세가 실제와 다른 프로젝트
- API 함수가 많고, 여러 개발자가 같은 쿼리 키 규칙으로 일해야 하는 팀
- 기존 코드를 크게 바꾸지 않고 TanStack Query 사용 규칙을 표준화하려는 팀

## 지금 되는 것

- `generate`: `sourceDir`의 최상위 함수마다 키 상수와 query, infinite query, mutation 옵션 팩토리를 `*Options.ts`로 생성합니다.
- 함수 이름 접두사로 생성 종류를 고릅니다. `get`·`list`·`fetch` 등은 query와 infinite query, `create`·`update`·`delete` 등은 mutation, 그 밖의 이름은 query와 mutation입니다. `artifactsByName`과 `enabledArtifacts`로 직접 지정할 수 있습니다.
- infinite query 옵션은 다음 페이지 규칙을 `withOptions`의 `initialPageParam`·`getNextPageParam`으로 지정해 씁니다. 지정하지 않으면 첫 페이지만 불러옵니다.
- 인자가 둘 이상인 함수의 mutation에 변수 객체 타입과 `mapVariablesToArgs`를 생성합니다.
- `withOptions`로 `staleTime`, `select` 등을 덮어쓰고, 인자·반환·`select` 결과 타입이 추론됩니다.
- `generate --check`: 파일을 쓰지 않고 누락·변경·오래된 결과가 있으면 종료 코드 1을 반환합니다.
- `watch`: 소스, 설정 파일, 지정한 로컬 플러그인이 바뀌면 다시 생성합니다.
- 생성 파일 첫 줄의 소유 표시로 구분해, 표시 없는 기존 파일은 덮어쓰지 않고 오류로 처리합니다.

## 진행 예정

- **JSDoc으로 생성 종류 지정:** `/** @rqh mutation */`처럼 함수 옆에서 query·mutation을 정합니다. 지금은 설정의 `artifactsByName`으로 지정합니다.
- **infinite query 선택 생성:** 페이지네이션을 지원하는 함수에만 만들도록 기본값을 바꿉니다. 지금은 `enabledArtifacts`·`artifactsByName`으로 끕니다.
- **파일 이동에 흔들리지 않는 키:** 파일 위치와 무관한 키 네임스페이스를 지정해, 리팩터링이 캐시 키를 바꾸지 않게 합니다.
- **분석 범위 확장:** re-export barrel, 클래스·객체 메서드, 고차 함수가 반환한 함수.
- **React 외 프레임워크:** Vue, Solid, Svelte용 TanStack Query.
- **OpenAPI 선택 연동:** 명세가 있는 신규 API와 기존 함수를 한 설정에서 함께 생성.

<a id="quick-start"></a>

## 설치와 사용

```sh
npm install @uiwwsw/react-query-helper@^2 @tanstack/react-query react
npx @uiwwsw/react-query-helper init
```

생성 코드가 이 패키지를 import하므로 일반 dependency로 설치합니다(`-D` 사용 금지).

```ts
// rqh.config.ts
import type { AutoQueryConfig } from "@uiwwsw/react-query-helper/config";

export default {
sourceDir: "./libs",
outputDir: "./src/options",
template: { artifactStrategy: "smart" },
} satisfies AutoQueryConfig;
```

```ts
// libs/users/api.ts
export const getUser = async (id: string) => ({ id, name: "Ada" });
```

`npx @uiwwsw/react-query-helper generate`를 실행하면 `src/options/users/apiOptions.ts`가 생성됩니다.

```ts
// Generated by @uiwwsw/react-query-helper. DO NOT EDIT.
// Source root: "../../libs"
import { getUser } from "../../../libs/users/api";
import {
queryOption as __rqh_query,
infiniteOption as __rqh_infinite,
} from "@uiwwsw/react-query-helper";

export const getUserKey = ["users", "api", "getUser"] as const;
export const getUserQueryOption = __rqh_query(getUserKey, getUser);
export const getUserInfiniteQueryOption = __rqh_infinite(getUserKey, getUser);
```

생성 파일은 수정하지 않습니다. 고칠 때는 원본 API를 수정합니다. 사용:

```tsx
// src/UserName.tsx
import { useQuery } from "@tanstack/react-query";
import { getUserQueryOption } from "./options/users/apiOptions";

export function UserName({ id }: { id: string }) {
const user = useQuery(
getUserQueryOption.withOptions(
{ staleTime: 60_000, select: (data) => data.name },
id,
),
);

if (user.isPending) return <p>Loading...</p>;
if (user.isError) return <p>{user.error.message}</p>;
return <p>{user.data}</p>;
}
```

```ts
// 기존 QueryClient 인스턴스 client에서
await client.prefetchQuery(getUserQueryOption("u1"));
const cached = client.getQueryData(getUserQueryOption("u1").queryKey);
// { id: string; name: string } | undefined
```

API 인자는 캐시 키에 포함됩니다. 토큰이나 인증 헤더를 인자로 넘기지 마세요.

## 문서

- [설정과 사용 가이드](docs/REFERENCE.md): CLI, 설정, 생성 규칙, 런타임 옵션, 무한 쿼리, 1.x 이전
- [README에서 옮긴 상세](docs/GUIDE.md): 전체 기능 목록, 설치 단계별 설명, 예제 찾기 표, 지원 환경, 의존성, 데모
- [구성과 의존성](docs/ARCHITECTURE.md): 모듈 구조, 비슷한 도구와의 비교
- [저장소 검토 기록](docs/REVIEW.md) · [변경 이력](CHANGELOG.md) · [데모](https://react-query-helper.vercel.app/)

## 라이선스

[MIT License](LICENSE)
Loading
Loading