1.0.5 • Published 4 months ago

graphql-codegen-typescript-api-func v1.0.5

Weekly downloads
-
License
UNLICENSED
Repository
github
Last release
4 months ago

graphql-codegen-typescript-api-func

TypeScript에서 API 함수들을 생성해주는 GraphQL Code Generator 플러그인입니다.

예시

schema: 'schema.graphql'
documents:
  - './**/*.graphql'
generates:
  './src/api/index.ts':
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-query
      - graphql-codegen-typescript-api-func
      - add:
          content: '/* eslint-disable */'
    config:
      fetcher:
        func: './fetcher#fetcher'
        optionsType: 'GqlRequestOptions'
      hasReactQueryPlugin: true
      apiFuncPrefix: api_
// 아래와 같은 함수를 자동으로 생성합니다
export function api_getUser(
  variables: GetUserQueryVariables,
  options?: GqlRequestOptions,
) {
  return fetcher<GetUserQuery, GetUserQueryVariables>(
    GetUserDocument,
    variables,
    options,
  );
}

설정 가이드

  • npm install graphql-codegen-typescript-api-func --save-dev 로 패키지를 설치합니다.
  • graphql-codegen.yml과 같이, GraphQL codegen 설정 파일을 만듭니다. (위의 예제를 참고해주세요)
  • npx graphql-code-generator --config graphql-codegen.yml 를 실행해서 코드를 생성합니다.
    • package.jsonscripts에 추가해두면 더욱 편리합니다.

설정

기본적으로, graphql-codegen-typescript-api-functypescript-react-query 플러그인과 같이 사용하는 것을 전제로 개발했습니다. hasReactQueryPlugintrue로 지정하면, 별도로 부가적인 정보를 사용하지 않고 typescript-react-query가 생성하는 변수들에 의존합니다.

fetcher (또는 apiFuncFetcher)

func

funcfetcher(document, variables, options) 의 파라미터를 받는 API 호출 시 실행될 함수를 지정합니다.

구체적으로 fetcher가 참조하는 함수는 다음과 같은 타입을 가지고 있습니다:

function fetcher<TResponse, TVariables>(
  document: string,
  variables?: TVariables,
  options?: Options,
): () => Promise<TResponse> {
  // ...
}

typescript-react-query와 함께 사용할 수 있도록 () => Promise 처럼 함수를 1번 더 실행해야 하는 형태로 개발했습니다.

해당 함수를 fileName#method와 같이, 파일 경로와 메소드 명을 # 로 구분해서 입력하면 됩니다.

optionsType

API 함수에서 3번째로 받을 인자의 타입을 지정합니다. RequestOptions 와 같은 문자열을 입력하면, API 함수의 3번째 인자가 해당 타입으로 지정됩니다.

hasReactQueryPlugin

react-query 플러그인이 존재하므로, 필요한 변수를 직접 생성하지 않고 react-query 플러그인에 의존할 지 지정합니다.

hasReactQueryPlugin: true

apiFuncPrefix / apiFuncSuffix

API 함수의 처음/끝에 붙일 문자열을 지정합니다.

apiFuncPrefix: 'api_'
apiFuncSuffix: '_func'
# api_getDocument_func

apiFuncOmitOperationSuffix

API 함수 끝부분에 Query, Mutation 과 같은 접미어를 붙일 지를 지정합니다. 기본적으로 true 입니다.

apiFuncOmitOperationSuffix: false
# getDocumentQuery()
# getDocumentMutation()

apiFuncPascalCase

API 함수를 시작할 때 첫번째 글자가 대문자 (PascalCase) 인지를 지정합니다. 기본적으로 false입니다.

apiFuncPascalCase: true
# GetDocument()
1.0.5

4 months ago

1.0.4

4 months ago

1.0.3

4 months ago

1.0.2

4 months ago

1.0.1

4 months ago

1.0.0

4 months ago