[GraphQL Nexus] query 작성 시 resolve 에서 세번째 인자 ctx 자동완성 오류

STEVELOPER·2023년 1월 29일
0

GraphQL Nexus

목록 보기
1/1

GraphQL Nexus 란 GraphQL 을 좀 더 편리하고 확장성있게 사용할 수 있도록 도와주는 Javascript Library 이다.
Apollo Server, Prisma 와 같이 사용하던 도중 API 를 생성하기 위해
extendType 을 사용하는데 resolve 부분에서 resolve 의 세번째 인자인
context(ctx) 를 사용할때 schema 를 생성할 때나 ApolloServer 인스턴스를 생성할 때 제대로 연결해주었음에도 불구하고 자동완성이 안되는 문제가 발생했다.
이 문제에 대한 해결방법은 아래와 같다

export const schema = makeSchema({
  types,
  outputs: {
    typegen: join(__dirname, "..", "nexus-typegen.ts"),
    schema: join(__dirname, "..", "schema.graphql"),
  },
  contextType: {
    module: join(__dirname, "./context.ts"),
    export: "Context",
  },
});

상기 코드는 GraphQL Nexus 에서 schema 를 생성하는 부분인데,
contextType 을 명시하면 된다.
context.ts 의 코드는 하기와 같다

import { PrismaClient } from "@prisma/client";
import { db } from "./db";

export interface Context {
  db: PrismaClient;
}

export const context = {
  db,
};

db 는 db.ts 로 코드는 하기와 같다

import { PrismaClient } from "@prisma/client";

export const db = new PrismaClient();

결과적으로 이렇게 세개의 파일이 맞물려야 resolve 에서 자동완성 기능이 제대로 작동한다.

원인

원인은 Typescript 문제로 여겨진다.
makeSchema 를 통해 schema 를 생성할때 contextType 을 명시적으로 지정해주지 않아 resolve 에서 사용하는 ctx 가 형식을 제대로 인식하지 못해 발생한 문제로 보인다.
이 문제를 위의 코드에서 contextType 을 위치(module)와 type(interface) 의 이름(export)을 지정해줌으로써 해결할 수 있었다.

profile
JavaScript, Node.js, Express, React, React Native, GraphQL, Apollo, Prisma, MySQL

0개의 댓글