[graphQL] resolver

seokki kwon·2022년 9월 14일
0

정의

type Query {
  numberSix: Int! # Should always return the number 6 when queried
  numberSeven: Int! # Should always return 7
}

숫자를 리턴하는 Query가 정의되어있다.
아마 숫자를 반환하는 쿼리인듯하다

const resolvers = {
  Query: {
    numberSix() {
      return 6;
    },
    numberSeven() {
      return 7;
    }
  }
};

resolver 단일객체는 서버의 모든 확인자를 정의한다
이객체를 리졸버 맵 이라고 한다.

인수처리

type User {
  id: ID!
  name: String
}

type Query {
  user(id: ID!): User
}
const resolvers = {
  Query: {
    user(parent, args, context, info) {
      return users.find(user => user.id === args.id);
    }
  }
}

리졸버는 4개의 인수를 받을 수 있다.
클라이언트에서 변수로 전달한 값들은 args 라는 객체에 담겨져있다.

리졸버체인

# A library has a branch and books
type Library {
  branch: String!
  books: [Book!]
}

# A book has a title and author
type Book {
  title: String!
  author: Author!
}

# An author has a name
type Author {
  name: String!
}

type Query {
  libraries: [Library]
}

해당 쿼리가 있다고 가정하면
libraries 는 [Library] 를 반환함
[Library] 는 branch 와 [Book] 를 반환함
Book 은 author 를 반환

공식문서에 따르면
. 스키마에 따라 이 객체 필드 패턴은 임의의 깊이까지 계속해서 리졸버 체인 이라고 하는 것을 생성할 수 있습니다 .

클라이언트에서 날릴 수 있는 쿼리

query GetBooksByLibrary {
  libraries {
    books {
      author {
        name
      }
    }
  }
}

const { ApolloServer, gql } = require('apollo-server');
const {
  ApolloServerPluginLandingPageLocalDefault,
} = require('apollo-server-core');

// libries 실제데이터
const libraries = [
  {
    branch: 'downtown'
  },
  {
    branch: 'riverside'
  },
];

//  books 데이터
const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
    branch: 'riverside'
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
    branch: 'downtown'
  },
];

// Schema definition
const typeDefs = gql`

# A library has a branch and books
  type Library {
    branch: String!
    books: [Book!]
  }

  # A book has a title and author
  type Book {
    title: String!
    author: Author!
  }

  # An author has a name
  type Author {
    name: String!
  }

  # Queries can fetch a list of libraries
  type Query {
    libraries: [Library]
  }
`;

// Resolver map
const resolvers = {
  Query: {
    libraries() {

      // Return our hardcoded array of libraries
      return libraries;
    }
  },
  Library: {
    books(parent) {

      // Filter the hardcoded array of books to only include
      // books that are located at the correct branch
      return books.filter(book => book.branch === parent.branch);
    }
  },
  Book: {

    // The parent resolver (Library.books) returns an object with the
    // author's name in the "author" field. Return a JSON object containing
    // the name, because this field expects an object.
    author(parent) {
      return {
        name: parent.author
      };
    }
  }

  // Because Book.author returns an object with a "name" field,
  // Apollo Server's default resolver for Author.name will work.
  // We don't need to define one.
};

// Pass schema definition and resolvers to the
// ApolloServer constructor
const server = new ApolloServer({
  typeDefs,
  resolvers,
  csrfPrevention: true,
  cache: 'bounded',
  plugins: [
    ApolloServerPluginLandingPageLocalDefault({ embed: true }),
  ],
});

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

리졸버체인은 실제로 서버에서 실행을 해봐야겠다
실제로 프로젝트를 해보며 필요한건 공식문서로 찾아보면서 해보자.

아폴로서버 만들어서 해보기

import { ApolloServer } from "apollo-server-express";
import { gql } from "apollo-server-core";
import {
  ApolloServerPluginDrainHttpServer,
  ApolloServerPluginLandingPageLocalDefault,
} from "apollo-server-core";
import express from "express";
import http from "http";

const typeDefs = gql`
  type Book {
    title: String!
  }

  type Query {
    findBook: Book!
  }
`;

const resolvers = {
  Query: {
    findBook() {
      return { title: "graphQL" };
    },
  },
};

startApolloServer(typeDefs, resolvers);

async function startApolloServer(typeDefs, resolvers) {
  // Required logic for integrating with Express
  const app = express();
  // Our httpServer handles incoming requests to our Express app.
  // Below, we tell Apollo Server to "drain" this httpServer,
  // enabling our servers to shut down gracefully.
  const httpServer = http.createServer(app);

  // Same ApolloServer initialization as before, plus the drain plugin
  // for our httpServer.
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    csrfPrevention: true,
    cache: "bounded",
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      ApolloServerPluginLandingPageLocalDefault({ embed: true }),
    ],
  });

  // More required logic for integrating with Express
  await server.start();
  server.applyMiddleware({
    app,
    // By default, apollo-server hosts its GraphQL endpoint at the
    // server root. However, *other* Apollo Server packages host it at
    // /graphql. Optionally provide this to match apollo-server.
    path: "",
  });

  // Modified server startup
  await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
}

리졸버에서는 객체형태로 반환을 해줘야함

내일해볼것

  • apollo mysql 연결(prisma client)
  • 회원가입 jwt 처음부터 구현해보기
profile
웹 & 앱개발 기록

0개의 댓글