cd my-project/graphql-server
graphql-server
디렉토리에 package.json
추가npm init -y
graphql-server/package.json
스크립트 변경{
"Before change": "Before change",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"After change": "Before change",
"scripts": {
"dev": "nodemon index.jsx"
}
}
npm install graphql
yarn add graphql
npm install apollo-server
yarn add apollo-server
npm install apollo-server graphql
yarn add apollo-server graphql
const { ApolloServer, gql } = require('apollo-server');
// The GraphQL schema
const typeDefs = gql`
type Query {
"A simple type for getting started!"
hello: String
}
`;
// A map of functions which return data for the schema.
const resolvers = {
Query: {
hello: () => 'world',
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
npm run dev
const typeDefs = gql`
type Query {
hello: String
}
`;
GraphQL에서 사용하는 스키마의 대한 정의를 하는 곳이며 클라이언트에서 GraphQL로const resolvers = {
Query: {
hello: () => 'Hello World',
},
};
클라이언트에서 GraphQL 로 서버에 어떠한 요청을 할 때 해당 요청의 응답을 작성하는
곳 입니다. 클라이언트에서 GraphQL로 typeDef
가 정의한 요청에 알맞게 요청한다면
resolvers
는 "data": { "hello" : "Hello World" }
라는 응답을 하게 됩니다.
그리고 typeDef
와 resolvers
는 한쌍을 이루게 되어 있습니다.
typeDef
와 resolvers
작성한다음 ApolloServer
에 넣으면 서버가 완성이 됩니다.
const server = new ApolloServer({
typeDefs,
resolvers,
});
// React.js 의 styled-components 처럼
// 백틱안에 값을 정의하는 방법
const typeDefs = gql`
type Query {
hello: String
}
`;