Skip to content

Directives

Ahrim Yang edited this page Nov 30, 2020 · 6 revisions

์ž‘์„ฑ์ž: J113 ์–‘์•„๋ฆผ

Directives (์ง€์‹œ์–ด)

  • ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฟผ๋ฆฌ์˜ ๊ตฌ์กฐ์™€ ํ˜•ํƒœ๋ฅผ ๋™์ ์œผ๋กœ ๋ณ€๊ฒฝํ•˜๊ธฐ ์œ„ํ•œ GraphQL ์˜ ๊ธฐ๋Šฅ
  • version ๊ด€๋ฆฌ๋ฅผ @deprecated ๋“ฑ์„ ํ†ตํ•ด์„œ ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • field ๋‚˜ fragment๋“ฑ์— ์‚ฝ์ž… ๋  ์ˆ˜ ์žˆ๋‹ค.
  • Directives๊ฐ€ ์‚ฝ์ž…๋˜๋Š” ์ˆœ์„œ์— ๋”ฐ๋ผ์„œ ๋™์ž‘์ด ๋‹ฌ๋ผ์ง„๋‹ค.
  • Directive Definition: Directives ์ •์˜ ๋ฐฉ๋ฒ•

Default Directives

@skip

directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

# FIELD
query skipField($someTest: Boolean!) {
  users{
    name
    age
  }
  books{
    title
    author @skip(if: $someTest)
  }  
}
# INLINE_FRAGMENT
query skipFragmentInline($someTest: Boolean!) {
  users{
    name
    age
  }
  books @skip(if: $someTest){
    title
    author
  } 
}
# FRAGMENT_SPREAD
query skipFragment($someTest: Boolean!) {
  users{
    ...userField
  }
  books @skip(if: $someTest){
    ...bookField
  } 
}

fragment userField on User{
  name
  age
}
fragment bookField on Book{
  title
  author
}

@include

directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

# FIELD
query skipField($someTest: Boolean!) {
  users{
    name
    age
  }
  books{
    title
    author @include(if: $someTest)
  }  
}

@deprecated

directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ENUM_VALUE

#FIELD_DEFINITION
type ExampleType {
    newField: String
    oldField: String @deprecated(reason: "Use 'newField'.")
}
#ENUM_VALUE
enum AllowedColor {
    RED @deprecated
    GREEN
    BLUE
}

Custom Directives

  • Apollo server๊ฐ€ ์ง€์›ํ•˜๋Š” schemaDirectiveVisitor๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ custom directive๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • Implementing directives Examples: Custom Directives ์˜ˆ์‹œ
// Directive ์ •์˜
class UpperCaseDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
  //FiedlDefintion์— ๋Œ€ํ•œ ์ •์˜
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async function (...args) {
      const result = await resolve.apply(this, args);
      if (typeof result === 'string') {
        return result.toUpperCase();
      }
      return result;
    };
  }
}
// Directive ์ƒ์„ฑ ๋ฐ ์‚ฌ์šฉ
const typeDefs = gql`
  directive @upper on FIELD_DEFINITION

  type Query {
    hello: String @upper
  }
`;
//resolver
const resolvers = {
  Query: {
    hello: (parent, args, context) => {
      return 'Hello world!';
    },
  },
};
//ApolloServer์— custom directive ์ถ”๊ฐ€
const server = new ApolloServer({
  typeDefs,
  resolvers,
  schemaDirectives: {
    upper: UpperCaseDirective,
    upperCase: UpperCaseDirective
    //ํ•˜๋‚˜์˜ custom Directive class๋ฅผ ์—ฌ๋Ÿฌ๊ฐœ์˜ directives๋กœ ์ถ”๊ฐ€ ํ•  ์ˆ˜ ์žˆ์Œ
  }
});
  • Schema directives: graphql-tools ๋ฅผ ์ด์šฉํ•œ custom directives
Clone this wiki locally