${en?'Your API function':'기존 API 함수'}
${esc(examples[0].source)}diff --git a/.workspace/github.json b/.workspace/github.json index 7871a0e..18532ff 100644 --- a/.workspace/github.json +++ b/.workspace/github.json @@ -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" + ] } diff --git a/.workspace/showcase.json b/.workspace/showcase.json index 620a5a5..0194871 100644 --- a/.workspace/showcase.json +++ b/.workspace/showcase.json @@ -8,7 +8,7 @@ "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 함수에서 쿼리 키와 옵션 코드 생성", "함수 이름에 따라 조회용과 변경용 코드를 나눠 생성", @@ -16,7 +16,7 @@ "API 함수가 바뀌면 다시 생성하는 watch 모드", "CI에서 오래된 생성 파일을 찾아내는 검사 명령", "생성 규칙과 템플릿을 프로젝트에 맞게 변경", - "데모에서 원본 함수와 생성 결과 비교" + "설치 없이 브라우저에서 함수를 붙여 넣고 결과 확인" ], "status": "live", "page": { @@ -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 함수만 있는 경우를 위한 것입니다." ], @@ -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)." } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 580ae3d..99983f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.ko.md b/README.ko.md new file mode 100644 index 0000000..50e6bab --- /dev/null +++ b/README.ko.md @@ -0,0 +1,171 @@ +
+
+
+ 기존 TypeScript API 함수는 그대로 두고, 그 위의 TanStack Query 계층(쿼리 키·옵션)을 생성하고 동기화하는 코드 생성 도구 +
+ + + ++ 플레이그라운드 · + 구성과 의존성 · + npm · + 변경 이력 · + English +
+ +**OpenAPI 없이, 기존 API는 그대로, Query 계층은 자동으로.** 이미 쓰고 있는 TypeScript API 함수에서 쿼리 키와 TanStack Query v5 옵션 팩토리(`queryOptions`, `infiniteQueryOptions`, `mutationOptions`)를 생성하고, API가 바뀌면 다시 맞춥니다. + + + +**[브라우저에서 바로 써 보기 →](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와 기존 함수를 한 설정에서 함께 생성. + + + +## 설치와 사용 + +```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) returnLoading...
; + if (user.isError) return{user.error.message}
; + return{user.data}
; +} +``` + +```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) diff --git a/README.md b/README.md index e417950..cb6e516 100644 --- a/README.md +++ b/README.md @@ -8,89 +8,94 @@- 기존 TypeScript API 함수는 그대로 두고, 그 위의 TanStack Query 계층(쿼리 키·옵션)을 생성하고 동기화하는 코드 생성 도구 + TanStack Query codegen without OpenAPI: a query key factory and queryOptions generator for the TypeScript API functions you already have
- 데모 · - 구성과 의존성 · + Playground · + Architecture · npm · - 변경 이력 · - English + Changelog · + 한국어
-> **버전 안내:** 이 문서는 **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-게시-전-소스에서-설치하기)할 수 있습니다. +React Query Helper is a TanStack Query (React Query) v5 code generator: it reads your existing TypeScript API functions and writes the query keys and `queryOptions`, `infiniteQueryOptions` and `mutationOptions` factories for them. No OpenAPI or Swagger spec needed, and your fetch or axios layer stays as it is. When the API changes, `watch` regenerates the files and `generate --check` catches stale output in CI. -**OpenAPI 없이, 기존 API는 그대로, Query 계층은 자동으로.** 이미 쓰고 있는 TypeScript API 함수에서 쿼리 키와 TanStack Query v5 옵션 팩토리(`queryOptions`, `infiniteQueryOptions`, `mutationOptions`)를 생성하고, API가 바뀌면 다시 맞춥니다. + + +**[Try it in the browser →](https://react-query-helper.vercel.app/en/#demo)** Paste an API function and see the generated keys and options. Nothing to install. + +> **Version notice:** This README describes **2.x**. Check the npm badge above for the published version. If you use 1.x, read the [1.3.0 docs](https://github.com/uiwwsw/react-query-helper/blob/v1.3.0/README_EN.md) and [migration guide](https://github.com/uiwwsw/react-query-helper/blob/main/docs/REFERENCE_EN.md#migrating-from-1x). To try changes not yet published, [install from source](https://github.com/uiwwsw/react-query-helper/blob/main/docs/REFERENCE_EN.md#install-from-source-before-npm-publication). -## 왜 필요한가 +## Why React Query Helper? -TanStack Query는 `queryOptions`로 쿼리 키와 조회 함수를 묶어 재사용하는 방식을 공식으로 제공합니다. 다만 그 연결은 API 함수마다 사람이 직접 써야 합니다. +TanStack Query already provides `queryOptions` for reusable, type-safe query definitions. But you still connect each API function to those options by hand: ```ts export const userOptions = (id: string) => queryOptions({ queryKey: ["users", id], queryFn: () => getUser(id) }); ``` -API 함수가 수백 개가 되고 여러 사람이 함께 관리하면, 키 이름 규칙, 함수와 옵션의 연결, 인자가 바뀔 때의 동기화가 매번 반복되는 일이 됩니다. React Query Helper는 이 연결을 생성기로 고정합니다. 캐싱, 재시도, 데이터 요청은 지금처럼 TanStack Query가 하고, 이 도구는 그 앞의 연결 코드만 만듭니다. +Across hundreds of API functions and several developers, key naming, the link between functions and options, and keeping them in sync when arguments change become repetitive work. React Query Helper fixes that connection in a generator. TanStack Query still handles caching, retries and fetching; this tool generates only the code that connects your API to it. -## 다른 도구와 다른 점 +## How it differs -- **기존 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`)을 바꿀 수 있습니다. +- **Your API layer stays.** Generated files go to `outputDir` and only import your API functions, so existing `fetch` or axios wrappers with auth headers, interceptors, error handling and response transforms, and your business logic, stay as they are. [Orval](https://orval.dev), [Kubb](https://kubb.dev) and [Hey API](https://heyapi.dev) generate the API functions themselves from an OpenAPI spec, so hand-written API functions are replaced by generated ones (you can plug in your own fetch instance). +- **No spec required.** The input is the TypeScript functions you already have, including projects whose OpenAPI or Swagger spec is missing or out of date. +- **One key convention, automatically.** `getUser` in `libs/users/api.ts` becomes `["users", "api", "getUser"]`, so developers stop inventing their own key names. [`@lukemorales/query-key-factory`](https://github.com/lukemorales/query-key-factory) needs the key structure declared by hand; this tool also generates the option factories. +- **No repeated type declarations.** Arguments, return values and `select` results are inferred from the original function. +- **Generated code is ordinary TypeScript.** Real `.ts` files, not runtime API discovery, so they show up in code review and you can jump to definitions in your IDE. There is no extra cache or query engine. +- **API and query layer stay in sync.** `watch` regenerates on API changes, and `generate --check` catches stale generated files in CI. +- **Adapts to your project.** Choose artifacts per function (`artifactsByName`), or replace the analyzer (`customAnalyzerPath`) and template (`customTemplatePath`). -## 이런 프로젝트에 맞습니다 +## Made for projects like these -- 인증·에러 처리가 들어간 `fetch`·axios API 계층이 이미 있는 프로젝트 -- 백엔드가 OpenAPI 명세를 제공하지 않거나 명세가 실제와 다른 프로젝트 -- API 함수가 많고, 여러 개발자가 같은 쿼리 키 규칙으로 일해야 하는 팀 -- 기존 코드를 크게 바꾸지 않고 TanStack Query 사용 규칙을 표준화하려는 팀 +- An existing `fetch` or axios API layer with auth and error handling +- A backend without an OpenAPI spec, or with one that does not match reality +- Many API functions and several developers who need one query key convention +- Teams standardizing TanStack Query usage without rewriting existing code -## 지금 되는 것 +## What works now -- `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`: 소스, 설정 파일, 지정한 로컬 플러그인이 바뀌면 다시 생성합니다. -- 생성 파일 첫 줄의 소유 표시로 구분해, 표시 없는 기존 파일은 덮어쓰지 않고 오류로 처리합니다. +- `generate`: for each top-level function in `sourceDir`, writes a key constant and query, infinite query and mutation option factories to `*Options.ts`. +- The function-name prefix picks the artifacts: `get`, `list`, `fetch` and similar get query and infinite query; `create`, `update`, `delete` and similar get a mutation; other names get query and mutation. `artifactsByName` and `enabledArtifacts` set them explicitly. +- Infinite query options take their paging rules from `withOptions` (`initialPageParam`, `getNextPageParam`); without them only the first page loads. +- Mutations of functions with two or more arguments get a variables object type and `mapVariablesToArgs`. +- `withOptions` overrides `staleTime`, `select` and others, with argument, return and `select` result types inferred. +- `generate --check` writes nothing and exits with code 1 when output is missing, changed or stale. +- `watch` regenerates when sources, the config or listed local plugins change. +- An ownership header on the first line marks generated files; unmarked existing files are never overwritten. -## 진행 예정 +## Planned -- **JSDoc으로 생성 종류 지정:** `/** @rqh mutation */`처럼 함수 옆에서 query·mutation을 정합니다. 지금은 설정의 `artifactsByName`으로 지정합니다. -- **infinite query 선택 생성:** 페이지네이션을 지원하는 함수에만 만들도록 기본값을 바꿉니다. 지금은 `enabledArtifacts`·`artifactsByName`으로 끕니다. -- **파일 이동에 흔들리지 않는 키:** 파일 위치와 무관한 키 네임스페이스를 지정해, 리팩터링이 캐시 키를 바꾸지 않게 합니다. -- **생성 결과 미리보기:** 데모에서 API 함수를 붙여 넣으면 생성될 키와 옵션을 설치 전에 보여 줍니다. -- **분석 범위 확장:** re-export barrel, 클래스·객체 메서드, 고차 함수가 반환한 함수. -- **React 외 프레임워크:** Vue, Solid, Svelte용 TanStack Query. -- **OpenAPI 선택 연동:** 명세가 있는 신규 API와 기존 함수를 한 설정에서 함께 생성. +- **Choose artifacts with JSDoc,** such as `/** @rqh mutation */` next to the function. Today `artifactsByName` in the config does this. +- **Infinite queries on request,** generated only for functions that paginate. Today `enabledArtifacts` or `artifactsByName` turn them off. +- **Keys that survive file moves,** with a namespace independent of the file path so refactoring does not change cache keys. +- **Wider analysis:** re-export barrels, class and object methods, functions returned by higher-order functions. +- **Beyond React:** TanStack Query for Vue, Solid and Svelte. +- **Optional OpenAPI input,** generating new spec-based APIs and existing functions from one config. -## 설치와 사용 +## Install and Use ```sh npm install @uiwwsw/react-query-helper@^2 @tanstack/react-query react npx @uiwwsw/react-query-helper init ``` -생성 코드가 이 패키지를 import하므로 일반 dependency로 설치합니다(`-D` 사용 금지). +Generated code imports this package, so install it as a regular dependency (do not use `-D`). ```ts // rqh.config.ts @@ -108,7 +113,7 @@ export default { export const getUser = async (id: string) => ({ id, name: "Ada" }); ``` -`npx @uiwwsw/react-query-helper generate`를 실행하면 `src/options/users/apiOptions.ts`가 생성됩니다. +Running `npx @uiwwsw/react-query-helper generate` writes `src/options/users/apiOptions.ts`. ```ts // Generated by @uiwwsw/react-query-helper. DO NOT EDIT. @@ -124,7 +129,7 @@ export const getUserQueryOption = __rqh_query(getUserKey, getUser); export const getUserInfiniteQueryOption = __rqh_infinite(getUserKey, getUser); ``` -생성 파일은 수정하지 않습니다. 고칠 때는 원본 API를 수정합니다. 사용: +Do not edit the generated file; change the source API instead. Usage: ```tsx // src/UserName.tsx @@ -146,21 +151,21 @@ export function UserName({ id }: { id: string }) { ``` ```ts -// 기존 QueryClient 인스턴스 client에서 +// With your existing QueryClient instance, client await client.prefetchQuery(getUserQueryOption("u1")); const cached = client.getQueryData(getUserQueryOption("u1").queryKey); // { id: string; name: string } | undefined ``` -API 인자는 캐시 키에 포함됩니다. 토큰이나 인증 헤더를 인자로 넘기지 마세요. +API arguments become part of the cache key. Do not pass tokens or authorization headers as arguments. -## 문서 +## Docs -- [설정과 사용 가이드](docs/REFERENCE.md): CLI, 설정, 생성 규칙, 런타임 옵션, 무한 쿼리, 1.x 이전 -- [README에서 옮긴 상세](docs/GUIDE.md): 전체 기능 목록, 설치 단계별 설명, 예제 찾기 표, 지원 환경, 의존성, 데모 -- [구성과 의존성](docs/ARCHITECTURE.md): 모듈 구조, 비슷한 도구와의 비교 -- [저장소 검토 기록](docs/REVIEW.md) · [변경 이력](CHANGELOG.md) · [데모](https://react-query-helper.vercel.app/) +- [Configuration and usage reference](docs/REFERENCE_EN.md): CLI, configuration, generation rules, runtime options, infinite queries, migrating from 1.x +- [Sections moved from the README](docs/GUIDE_EN.md): full feature list, step-by-step install, recipe table, compatibility, dependencies, demo +- [Architecture and dependencies](docs/ARCHITECTURE_EN.md): module layout, comparison with similar tools +- [Repository review](docs/REVIEW.md) · [Changelog](CHANGELOG.md) · [Demo](https://react-query-helper.vercel.app/en/) -## 라이선스 +## License [MIT License](LICENSE) diff --git a/README_EN.md b/README_EN.md deleted file mode 100644 index 89ac3f3..0000000 --- a/README_EN.md +++ /dev/null @@ -1,166 +0,0 @@ -
-
-
- Keep your existing TypeScript API functions; generate and sync the TanStack Query layer (query keys and options) on top of them -
- - - -- Demo · - Architecture · - npm · - Changelog · - 한국어 -
- -> **Version notice:** This README describes **2.x**. Check the npm badge above for the published version. If you use 1.x, read the [1.3.0 docs](https://github.com/uiwwsw/react-query-helper/blob/v1.3.0/README_EN.md) and [migration guide](https://github.com/uiwwsw/react-query-helper/blob/main/docs/REFERENCE_EN.md#migrating-from-1x). To try changes not yet published, [install from source](https://github.com/uiwwsw/react-query-helper/blob/main/docs/REFERENCE_EN.md#install-from-source-before-npm-publication). - -**No OpenAPI required. Keep your existing API. Automate the query layer.** React Query Helper generates query keys and TanStack Query v5 option factories (`queryOptions`, `infiniteQueryOptions`, `mutationOptions`) from the TypeScript API functions you already have, and regenerates them when the API changes. - -## Why React Query Helper? - -TanStack Query already provides `queryOptions` for reusable, type-safe query definitions. But you still connect each API function to those options by hand: - -```ts -export const userOptions = (id: string) => - queryOptions({ queryKey: ["users", id], queryFn: () => getUser(id) }); -``` - -Across hundreds of API functions and several developers, key naming, the link between functions and options, and keeping them in sync when arguments change become repetitive work. React Query Helper fixes that connection in a generator. TanStack Query still handles caching, retries and fetching; this tool generates only the code that connects your API to it. - -## How it differs - -- **Your API layer stays.** Generated files go to `outputDir` and only import your API functions, so existing `fetch` or axios wrappers with auth headers, interceptors, error handling and response transforms, and your business logic, stay as they are. [Orval](https://orval.dev), [Kubb](https://kubb.dev) and [Hey API](https://heyapi.dev) generate the API functions themselves from an OpenAPI spec, so hand-written API functions are replaced by generated ones (you can plug in your own fetch instance). -- **No spec required.** The input is the TypeScript functions you already have, including projects whose OpenAPI or Swagger spec is missing or out of date. -- **One key convention, automatically.** `getUser` in `libs/users/api.ts` becomes `["users", "api", "getUser"]`, so developers stop inventing their own key names. [`@lukemorales/query-key-factory`](https://github.com/lukemorales/query-key-factory) needs the key structure declared by hand; this tool also generates the option factories. -- **No repeated type declarations.** Arguments, return values and `select` results are inferred from the original function. -- **Generated code is ordinary TypeScript.** Real `.ts` files, not runtime API discovery, so they show up in code review and you can jump to definitions in your IDE. There is no extra cache or query engine. -- **API and query layer stay in sync.** `watch` regenerates on API changes, and `generate --check` catches stale generated files in CI. -- **Adapts to your project.** Choose artifacts per function (`artifactsByName`), or replace the analyzer (`customAnalyzerPath`) and template (`customTemplatePath`). - -## Made for projects like these - -- An existing `fetch` or axios API layer with auth and error handling -- A backend without an OpenAPI spec, or with one that does not match reality -- Many API functions and several developers who need one query key convention -- Teams standardizing TanStack Query usage without rewriting existing code - -## What works now - -- `generate`: for each top-level function in `sourceDir`, writes a key constant and query, infinite query and mutation option factories to `*Options.ts`. -- The function-name prefix picks the artifacts: `get`, `list`, `fetch` and similar get query and infinite query; `create`, `update`, `delete` and similar get a mutation; other names get query and mutation. `artifactsByName` and `enabledArtifacts` set them explicitly. -- Infinite query options take their paging rules from `withOptions` (`initialPageParam`, `getNextPageParam`); without them only the first page loads. -- Mutations of functions with two or more arguments get a variables object type and `mapVariablesToArgs`. -- `withOptions` overrides `staleTime`, `select` and others, with argument, return and `select` result types inferred. -- `generate --check` writes nothing and exits with code 1 when output is missing, changed or stale. -- `watch` regenerates when sources, the config or listed local plugins change. -- An ownership header on the first line marks generated files; unmarked existing files are never overwritten. - -## Planned - -- **Choose artifacts with JSDoc,** such as `/** @rqh mutation */` next to the function. Today `artifactsByName` in the config does this. -- **Infinite queries on request,** generated only for functions that paginate. Today `enabledArtifacts` or `artifactsByName` turn them off. -- **Keys that survive file moves,** with a namespace independent of the file path so refactoring does not change cache keys. -- **Preview before installing:** paste API functions into the demo and see the keys and options that would be generated. -- **Wider analysis:** re-export barrels, class and object methods, functions returned by higher-order functions. -- **Beyond React:** TanStack Query for Vue, Solid and Svelte. -- **Optional OpenAPI input,** generating new spec-based APIs and existing functions from one config. - - - -## Install and Use - -```sh -npm install @uiwwsw/react-query-helper@^2 @tanstack/react-query react -npx @uiwwsw/react-query-helper init -``` - -Generated code imports this package, so install it as a regular dependency (do not use `-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" }); -``` - -Running `npx @uiwwsw/react-query-helper generate` writes `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); -``` - -Do not edit the generated file; change the source API instead. Usage: - -```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) returnLoading...
; - if (user.isError) return{user.error.message}
; - return{user.data}
; -} -``` - -```ts -// With your existing QueryClient instance, client -await client.prefetchQuery(getUserQueryOption("u1")); -const cached = client.getQueryData(getUserQueryOption("u1").queryKey); -// { id: string; name: string } | undefined -``` - -API arguments become part of the cache key. Do not pass tokens or authorization headers as arguments. - -## Docs - -- [Configuration and usage reference](docs/REFERENCE_EN.md): CLI, configuration, generation rules, runtime options, infinite queries, migrating from 1.x -- [Sections moved from the README](docs/GUIDE_EN.md): full feature list, step-by-step install, recipe table, compatibility, dependencies, demo -- [Architecture and dependencies](docs/ARCHITECTURE_EN.md): module layout, comparison with similar tools -- [Repository review](docs/REVIEW.md) · [Changelog](CHANGELOG.md) · [Demo](https://react-query-helper.vercel.app/en/) - -## License - -[MIT License](LICENSE) diff --git a/assets/README.md b/assets/README.md index 7944031..e706a10 100644 --- a/assets/README.md +++ b/assets/README.md @@ -1,6 +1,6 @@ # Brand Assets -[Back to the README](../README.md) +[Back to the README](../README.ko.md)  diff --git a/assets/playground.gif b/assets/playground.gif new file mode 100644 index 0000000..ee77cd5 Binary files /dev/null and b/assets/playground.gif differ diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b32d89f..d3feab5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,6 +1,6 @@ # 구성과 의존성 -[README로 돌아가기](../README.md) · [English](ARCHITECTURE_EN.md) · [설정과 사용 가이드](REFERENCE.md) +[README로 돌아가기](../README.ko.md) · [English](ARCHITECTURE_EN.md) · [설정과 사용 가이드](REFERENCE.md) 이 문서는 2.x 소스를 읽고 정리한 내용입니다. 각 모듈이 하는 일, 의존하는 패키지, TanStack Query와 비슷한 도구와의 관계를 적었습니다. @@ -94,13 +94,13 @@ API 소스 파일(.ts/.tsx) | `scripts/build-site.mjs` | 실제 분석기와 생성기로 예제 출력을 만들어 한국어·영어 데모 페이지를 생성합니다 | | `scripts/check-site.mjs` | 생성된 데모 페이지의 canonical, hreflang, sitemap, 폰트 등을 검사합니다 | | `test/` | Node 테스트 러너와 `tsc` 타입 테스트. README 예제를 실제로 생성하고 타입 검사합니다 | -| `site/` | 데모 페이지의 예제 입력(`examples.ts`), 스타일, 스크립트, 정적 자산 | +| `site/` | 데모 페이지의 플레이그라운드(`playground.ts`)와 예제(`presets.mjs`), 스타일, 정적 자산 | | `assets/` | 로고와 README 배너 SVG | | `docs/` | 이 문서, 설정 가이드(`REFERENCE*.md`), 검토 기록(`REVIEW.md`), 데모 배포 메모(`SEO.md`) | | `.github/` | CI, 게시, 문서 위생 검사 워크플로와 검사 스크립트 | | `vercel.json`, `.workspace/` | 데모 사이트 배포 설정 | -npm 패키지에 들어가는 것은 `dist/`, `README_EN.md`, `CHANGELOG.md`이고, npm이 `README.md`, `LICENSE`, `package.json`을 자동으로 포함합니다(`package.json`의 `files` 기준). +npm 패키지에 들어가는 것은 `dist/`, `README.ko.md`, `CHANGELOG.md`이고, npm이 `README.md`, `LICENSE`, `package.json`을 자동으로 포함합니다(`package.json`의 `files` 기준). ## 의존성 diff --git a/docs/ARCHITECTURE_EN.md b/docs/ARCHITECTURE_EN.md index 0d28527..526585d 100644 --- a/docs/ARCHITECTURE_EN.md +++ b/docs/ARCHITECTURE_EN.md @@ -1,6 +1,6 @@ # Architecture and Dependencies -[Back to README](../README_EN.md) · [한국어](ARCHITECTURE.md) · [Configuration and usage guide](REFERENCE_EN.md) +[Back to README](../README.md) · [한국어](ARCHITECTURE.md) · [Configuration and usage guide](REFERENCE_EN.md) This page was written from the 2.x source. It lists what each module does, which packages it depends on, and how it relates to TanStack Query and similar tools. @@ -94,13 +94,13 @@ It contains no `QueryClient`, caching, retry logic or hooks. | `scripts/build-site.mjs` | Builds the Korean and English demo pages, with example output from the real analyzer and generator | | `scripts/check-site.mjs` | Checks the built demo pages: canonical, hreflang, sitemap, fonts | | `test/` | Node test runner files and `tsc` type tests. README examples are generated and type-checked for real | -| `site/` | Demo page example input (`examples.ts`), styles, script and static assets | +| `site/` | Demo playground (`playground.ts`), example files (`presets.mjs`), styles and static assets | | `assets/` | Logo and README banner SVGs | | `docs/` | This page, the configuration guides (`REFERENCE*.md`), the review notes (`REVIEW.md`) and demo deployment notes (`SEO.md`) | | `.github/` | CI, publish and documentation-hygiene workflows, and the check script | | `vercel.json`, `.workspace/` | Demo site deployment settings | -The npm package contains `dist/`, `README_EN.md` and `CHANGELOG.md` (the `files` field), and npm adds `README.md`, `LICENSE` and `package.json` automatically. +The npm package contains `dist/`, `README.ko.md` and `CHANGELOG.md` (the `files` field), and npm adds `README.md`, `LICENSE` and `package.json` automatically. ## Dependencies diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 38b8118..4355eeb 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1,6 +1,6 @@ # README에서 옮긴 상세 내용 -[README로 돌아가기](../README.md) · [English](GUIDE_EN.md) · [설정과 사용 가이드](REFERENCE.md) +[README로 돌아가기](../README.ko.md) · [English](GUIDE_EN.md) · [설정과 사용 가이드](REFERENCE.md) README를 줄이면서 옮긴 절입니다. 내용은 이전 README와 같습니다. diff --git a/docs/GUIDE_EN.md b/docs/GUIDE_EN.md index c886139..f7dec9e 100644 --- a/docs/GUIDE_EN.md +++ b/docs/GUIDE_EN.md @@ -1,6 +1,6 @@ # Sections moved out of the README -[Back to README](../README_EN.md) · [한국어](GUIDE.md) · [Reference](REFERENCE_EN.md) +[Back to README](../README.md) · [한국어](GUIDE.md) · [Reference](REFERENCE_EN.md) These sections were moved here when the README was shortened. The content is unchanged. diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 0f18f31..f08b4aa 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -1,8 +1,8 @@ # 설정과 사용 가이드 -[README로 돌아가기](../README.md) · [English](REFERENCE_EN.md) · [변경 이력](../CHANGELOG.md) +[README로 돌아가기](../README.ko.md) · [English](REFERENCE_EN.md) · [변경 이력](../CHANGELOG.md) -2.x 기준 상세 문서입니다. 처음 사용한다면 [빠른 시작](../README.md#quick-start)을 먼저 읽으세요. +2.x 기준 상세 문서입니다. 처음 사용한다면 [빠른 시작](../README.ko.md#quick-start)을 먼저 읽으세요. [CLI](#cli) · [설정](#설정) · [생성 규칙](#생성-규칙) · [런타임 옵션](#런타임-옵션) · [무한 쿼리](#무한-쿼리) · [1.x 이전](#1x에서-이전) @@ -294,8 +294,8 @@ npm test npm pack ``` -생성된 `uiwwsw-react-query-helper-2.0.4.tgz`의 실제 경로를 사용해 **앱 디렉토리에서** -`npm install /absolute/path/to/uiwwsw-react-query-helper-2.0.4.tgz`를 실행합니다. +생성된 `uiwwsw-react-query-helper-2.1.0.tgz`의 실제 경로를 사용해 **앱 디렉토리에서** +`npm install /absolute/path/to/uiwwsw-react-query-helper-2.1.0.tgz`를 실행합니다. React와 TanStack Query도 앱에 설치한 뒤 README의 `init` 단계부터 진행하세요. `npm pack`은 prepack 빌드를 실행하므로 배포에 필요한 dist도 포함됩니다. diff --git a/docs/REFERENCE_EN.md b/docs/REFERENCE_EN.md index 58c0925..2969ea3 100644 --- a/docs/REFERENCE_EN.md +++ b/docs/REFERENCE_EN.md @@ -1,8 +1,8 @@ # Configuration and Usage Guide -[Back to README](../README_EN.md) · [한국어](REFERENCE.md) · [Changelog](../CHANGELOG.md) +[Back to README](../README.md) · [한국어](REFERENCE.md) · [Changelog](../CHANGELOG.md) -This reference describes 2.x. New users should start with the [quick start](../README_EN.md#quick-start). +This reference describes 2.x. New users should start with the [quick start](../README.md#quick-start). [CLI](#cli) · [Configuration](#configuration) · [Generation](#generation-rules) · [Options](#runtime-options) · [Infinite queries](#infinite-queries) · [Migration](#migrating-from-1x) @@ -296,7 +296,7 @@ npm pack ``` From **your application directory**, install the resulting tarball using its actual path: -`npm install /absolute/path/to/uiwwsw-react-query-helper-2.0.4.tgz`. +`npm install /absolute/path/to/uiwwsw-react-query-helper-2.1.0.tgz`. Also install React and TanStack Query in the application, then continue at the README's `init` step. The prepack build includes the required dist files in the tarball. diff --git a/docs/SEO.md b/docs/SEO.md index 69c1381..823c129 100644 --- a/docs/SEO.md +++ b/docs/SEO.md @@ -2,7 +2,7 @@ Public origin: https://react-query-helper.vercel.app/. Korean `/`, English `/en/`. The library repository remains https://github.com/uiwwsw/react-query-helper and the npm package is @uiwwsw/react-query-helper. -`npm run build:site` builds the actual library, then generates static translated HTML and sample output using analyzeFile and generateOptionsCode. The browser selector switches among query, mutation and infinite-query examples generated from site/examples.ts; no fake backend or arbitrary code execution is involved. Package tests remain independent of the demo. +`npm run build:site` builds the actual library, then generates static translated HTML. The first example from site/presets.mjs is rendered into the page at build time with analyzeSource, generateOptionsCode and Prettier, so the output is visible before any script runs. site/playground.ts bundles the same analyzer, generator and Prettier for the browser and regenerates the output as the reader edits the source; it is loaded when the reader reaches the playground or the page is idle. No code is sent to a server. Package tests remain independent of the demo. Both pages provide descriptive titles, content, canonical URLs, reciprocal ko/en/x-default links, SoftwareApplication structured data, robots.txt and sitemap.xml. Keyword themes match TanStack Query v5 code generation, typed query keys, TypeScript APIs, query/mutation/infinite-query factories, watch and CI checks. API clients, caching and retries remain the application’s responsibility. diff --git a/package-lock.json b/package-lock.json index 8292e56..d180286 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@uiwwsw/react-query-helper", - "version": "2.0.4", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@uiwwsw/react-query-helper", - "version": "2.0.4", + "version": "2.1.0", "license": "MIT", "dependencies": { "chokidar": "^4.0.3", diff --git a/package.json b/package.json index 37dda8d..9e392ab 100644 --- a/package.json +++ b/package.json @@ -1,27 +1,34 @@ { "name": "@uiwwsw/react-query-helper", - "version": "2.0.4", + "version": "2.1.0", "module": "dist/index.js", "type": "module", "types": "dist/index.d.ts", "main": "dist/index.js", "license": "MIT", - "description": "Generate and 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.", + "description": "TanStack Query codegen without OpenAPI: a query key factory and queryOptions generator. Reads your existing TypeScript API functions and writes query keys plus queryOptions, infiniteQueryOptions and mutationOptions for React Query v5, with watch mode and a CI check.", "keywords": [ "react-query", "tanstack-query", "tanstack-query-v5", - "react", - "typescript", - "codegen", - "code-generator", - "cli", + "tanstack-query-codegen", + "react-query-codegen", "query-key-factory", - "query-options", + "query-key-generator", + "queryoptions", + "queryoptions-generator", "mutation-options", "infinite-query", - "existing-api", - "no-openapi" + "codegen", + "code-generator", + "typescript", + "react", + "cli", + "no-openapi", + "openapi-alternative", + "orval-alternative", + "axios", + "fetch" ], "homepage": "https://react-query-helper.vercel.app/", "bugs": { @@ -34,7 +41,7 @@ "author": "uiwwsw", "files": [ "dist", - "README_EN.md", + "README.ko.md", "CHANGELOG.md" ], "bin": { diff --git a/scripts/build-site.mjs b/scripts/build-site.mjs index b64d54e..0e021bd 100644 --- a/scripts/build-site.mjs +++ b/scripts/build-site.mjs @@ -1,29 +1,34 @@ import { mkdir, readFile, writeFile, cp } from 'node:fs/promises'; -import { analyzeFile } from '../dist/core/analyzer.js'; +import { build } from 'esbuild'; +import prettier from 'prettier'; +import { analyzeSource } from '../dist/core/analyzer.js'; import { generateOptionsCode } from '../dist/core/generator.js'; +import { presets } from '../site/presets.mjs'; const out='site-dist', origin='https://react-query-helper.vercel.app'; const esc=text=>String(text).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"'); -const functions=analyzeFile('site/examples.ts'); -const source=await readFile('site/examples.ts','utf8'); -const examples=functions.map(info=>({name:info.name,source:source.split('\n').find(line=>line.includes(` ${info.name} =`)),output:generateOptionsCode([info],'./api',{keySegments:['users'],fileName:'api',templateImportPath:'@uiwwsw/react-query-helper'})})); -const usageConfig={service:'react-query-helper',origin,hosts:[new URL(origin).hostname],routes:[{match:'^/$',path:'/',name:'home_ko'},{match:'^/en/?$',path:'/en/',name:'home_en'}],sections:{demo:'examples'},controls:examples.map(e=>`example_${e.name}`),outbound:[{url:'https://github.com/uiwwsw/react-query-helper',name:'github'},{url:'https://www.npmjs.com/package/@uiwwsw/react-query-helper',name:'npm'}]}; +const header='// Generated by @uiwwsw/react-query-helper. DO NOT EDIT.\n// Source root: "../../libs"\n'; +const initial=presets[0].source; +const initialOutput=header+await prettier.format(generateOptionsCode(analyzeSource('api.ts',initial),'../../../libs/users/api',{keySegments:['users'],fileName:'api',templateImportPath:'@uiwwsw/react-query-helper'}),{parser:'typescript'}); +const usageConfig={service:'react-query-helper',origin,hosts:[new URL(origin).hostname],routes:[{match:'^/$',path:'/',name:'home_ko'},{match:'^/en/?$',path:'/en/',name:'home_en'}],sections:{demo:'playground'},controls:[...presets.map(p=>`example_${p.id}`),'playground_copy'],outbound:[{url:'https://github.com/uiwwsw/react-query-helper',name:'github'},{url:'https://www.npmjs.com/package/@uiwwsw/react-query-helper',name:'npm'}]}; const usageTag=``; await mkdir(`${out}/en`,{recursive:true});await cp('assets',`${out}/assets`,{recursive:true}); for(const en of [false,true]) { const lang=en?'en':'ko',path=en?'/en/':'/'; - const title=en?'React Query Helper — TanStack Query TypeScript Code Generator':'리액트쿼리헬퍼 — React Query·TanStack Query 코드 자동 생성'; - const desc=en?'Generate type-safe TanStack Query v5 query, mutation and infinite-query option factories from existing TypeScript API functions. See generated examples, watch mode and CI checks.':'기존 TypeScript API 함수에서 TanStack Query v5 query·mutation·무한 쿼리 옵션과 쿼리 키를 자동 생성하세요. React Query 반복 코드를 줄이고 watch·CI 검증을 연결하는 개발 도구입니다.'; - const guide=en?'README_EN.md':'README.md'; - const page=`TANSTACK QUERY V5 CODE GENERATOR
${esc(desc)}
${en?'View generated code':'생성 코드 보기'} ↓${en?'Quick start guide':'시작 가이드'} ↗TanStack Query v5 · TypeScript · React 18 / 19 · MIT
01 / GENERATOR OUTPUT
${en?'These examples are generated from this repository’s actual analyzer and code generator at build time. Select a function to inspect its source and output.':'이 예제는 저장소의 실제 분석기와 코드 생성기로 빌드할 때 만듭니다. 함수를 선택하면 원본과 생성 결과를 대조할 수 있습니다.'}
${esc(examples[0].source)}${esc(examples[0].output)}${en?'This is a code-generation preview, not a live backend. Configure pagination and forward AbortSignal explicitly for your API.':'실제 서버를 호출하는 화면이 아닌 코드 생성 미리보기입니다. 페이지네이션과 AbortSignal 전달은 API에 맞게 명시적으로 구성합니다.'}
02 / SETUP AND CI
${en?'Generate once, watch during development and check generated output in CI. Reuse factories with useQuery, prefetchQuery and cache reads.':'한 번 생성하고, 개발 중에는 watch로 갱신하고, CI에서는 생성 결과를 검사하세요. useQuery·prefetchQuery·캐시 조회에 동일한 팩토리를 재사용합니다.'}
npm install @uiwwsw/react-query-helper@^2 @tanstack/react-query react + const title=en?'React Query Helper: TanStack Query codegen without OpenAPI (queryOptions and query key generator)':'리액트쿼리헬퍼: OpenAPI 없이 TanStack Query 쿼리 키·옵션 자동 생성'; + const desc=en?'Generate TanStack Query v5 query keys, queryOptions, infiniteQueryOptions and mutationOptions from the TypeScript API functions you already have. No OpenAPI spec needed. Paste a function into the playground to see the output.':'이미 있는 TypeScript API 함수에서 TanStack Query v5 쿼리 키와 queryOptions, infiniteQueryOptions, mutationOptions를 만듭니다. OpenAPI 명세가 없어도 됩니다. 플레이그라운드에 함수를 붙여 넣으면 결과가 바로 나옵니다.'; + const guide=en?'README.md':'README.ko.md'; + const page=`${esc(title)} ${usageTag}${en?'Skip to the playground':'플레이그라운드로 건너뛰기'}react query helper
`; +npx @uiwwsw/react-query-helper generate --check TANSTACK QUERY V5 CODE GENERATOR
${en?'Query keys and options,
generated from TypeScript.':'쿼리 키와 옵션을
TypeScript 함수에서 생성합니다.'}${esc(desc)}
${en?'Try it in the browser':'브라우저에서 써 보기'} ↓${en?'Quick start guide':'시작 가이드'} ↗TanStack Query v5 · TypeScript · React 18 / 19 · MIT
01 / PLAYGROUND
${en?'Paste a function, get the query layer':'함수를 붙여 넣으면 쿼리 코드가 나옵니다'}
${en?'This runs the package’s own analyzer and generator in your browser, so the output is what
generatewould write. Your code stays on this page.':'패키지의 실제 분석기와 생성기를 브라우저에서 돌립니다. 오른쪽 결과는generate명령이 쓰는 파일과 같습니다. 입력한 코드는 이 페이지 밖으로 나가지 않습니다.'}${en?'Keys come from the path under
libs/and the function name.':'키는libs/아래 경로와 함수 이름으로 만들어집니다.'} src/options/users/apiOptions.ts${esc(initialOutput)}02 / SETUP AND CI
${en?'Install, generate, watch and check':'설치, 생성, watch, 검사'}
${en?'Generate once, watch during development and check generated output in CI. Reuse factories with useQuery, prefetchQuery and cache reads.':'한 번 생성하고, 개발 중에는 watch로 갱신하고, CI에서는 생성 결과를 검사하세요. useQuery·prefetchQuery·캐시 조회에 동일한 팩토리를 재사용합니다.'}
npm install @uiwwsw/react-query-helper@^2 @tanstack/react-query react npx @uiwwsw/react-query-helper init npx @uiwwsw/react-query-helper generate npx @uiwwsw/react-query-helper watch -npx @uiwwsw/react-query-helper generate --check${en?'What does React Query Helper generate?':'React Query Helper는 무엇을 생성하나요?'}
${en?'Typed query keys and query, mutation and infinite-query option factories from top-level TypeScript API functions. Keep your existing HTTP client. It does not replace TanStack Query caching or retries.':'TypeScript 최상위 API 함수에서 타입이 있는 쿼리 키와 query·mutation·infinite query 옵션 팩토리를 생성합니다. 기존 HTTP 클라이언트를 유지하며 TanStack Query의 캐시·재시도 동작은 대체하지 않습니다.'}
${en?'Configuration, pagination and migration':'설정·페이지네이션·마이그레이션'} ↗
${en?'Typed query keys and query, mutation and infinite-query option factories from top-level TypeScript API functions. Keep your existing HTTP client. It does not replace TanStack Query caching or retries.':'TypeScript 최상위 API 함수에서 타입이 있는 쿼리 키와 query·mutation·infinite query 옵션 팩토리를 생성합니다. 기존 HTTP 클라이언트를 유지하며 TanStack Query의 캐시·재시도 동작은 대체하지 않습니다.'}
${en?'Configuration, pagination and migration':'설정·페이지네이션·마이그레이션'} ↗