[nodejs] GraphQL 쿼리 언어 디렉티브 활용 예제

GraphQL은 강력한 쿼리 언어로, 디렉티브를 사용하여 쿼리의 동작을 제어할 수 있습니다. 디렉티브를 활용하면 쿼리의 결과를 가공하거나 캐시 제어 등의 다양한 기능을 수행할 수 있습니다.

이 예제에서는 JavaScript와 Node.js를 사용하여 GraphQL 쿼리 언어 디렉티브를 활용하는 방법을 살펴봅니다.

1. 디렉티브 정의하기

먼저 GraphQL 스키마에서 디렉티브를 정의합니다. 다음은 간단한 캐싱을 위한 @cache 디렉티브의 예제입니다.

directive @cache(maxAge: Int) on FIELD_DEFINITION

위에서 @cachemaxAge 매개변수를 가지며 FIELD_DEFINITION에서 사용할 수 있도록 정의되었습니다.

2. 디렉티브 적용하기

이제 디렉티브를 실제 쿼리에 적용해보겠습니다.

query {
  products @cache(maxAge: 60) {
    id
    name
  }
}

위의 쿼리에서 @cache 디렉티브를 사용하여 products 필드의 결과를 60초 동안 캐싱합니다.

3. 디렉티브 구현하기

마지막으로, Node.js에서 GraphQL 서버를 구현하고 디렉티브를 처리합니다.

const { ApolloServer, gql, SchemaDirectiveVisitor } = require('apollo-server');
const { defaultFieldResolver } = require('graphql');

class CacheDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field;
    const { maxAge } = this.args;
    field.resolve = async function (source, args, context, info) {
      // 캐싱 로직 구현
      const cacheKey = info.fieldName;
      const cachedData = await cache.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }
      const result = await resolve.call(this, source, args, context, info);
      await cache.set(cacheKey, result, { ttl: maxAge });
      return result;
    };
  }
}

const typeDefs = gql`
  directive @cache(maxAge: Int) on FIELD_DEFINITION
  
  type Product {
    id: ID
    name: String
  }
  
  type Query {
    products: [Product] @cache(maxAge: 60)
  }
`;

const resolvers = {
  Query: {
    products: () => {
      // 제품 목록 조회 로직
      return someProductData;
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  schemaDirectives: {
    cache: CacheDirective
  }
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

위 코드에서 CacheDirective 클래스는 @cache 디렉티브를 처리하는 방법을 정의하고, 이를 서버 구성 옵션으로 등록합니다.

이제 GraphQL 서버를 실행하고 쿼리를 실행하면 설정한 디렉티브에 따라 캐싱이 수행될 것입니다.

디렉티브를 활용하면 쿼리의 결과를 동적으로 제어하거나 다양한 기능을 추가할 수 있어서, GraphQL의 강력한 기능 중 하나로 평가받고 있습니다.

더 많은 디렉티브와 사용 예제를 확인하려면 GraphQL 공식 문서를 참고하세요.