1. GraphQL 스키마 정의
GraphQL에 스키마는 API의 구조를 정의합니다. 다음과 같은 예시로 작성할 수 있습니다.
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList
} = require('graphql');
;
// 가상 데이터
const users = [
{ id: '1', name: "John Doe", email: "abcd@abcd.com" },
{ id: '2', name: "Kanny" },
]
// UserType정의
const UserType = new GraphQLObjectType({
name: "User",
fields: {
id: { type: GraphQLString },
name: { type: GraphQLString },
email: { type: GraphQLString }
}
});
// RootQuery 정의
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
user: {
type: UserType,
args: { id: { type: GraphQLString }},
resolve(parent, args) {
// 데이터 베이스에 사용자 정보를 가져옴
return users.find(user => user.id === args.id);
}
},
users: {
type: new GraphQLList(UserType),
resolve(parent, args) {
return users;
}
}
}
});
// Mutation 정의
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {
type: UserType,
args: {
name: { type: GraphQLString } // 인자 정의
}, resolve(parent, args) {
const newUser = {
id: String(users.length + 1), // 새로운 ID 성성
name: args.name
};
users.push(newUser); // 사용자 추가
return newUser; // 추가된 사용자 반환
}
}
}
})
const schema = new GraphQLSchema({
query: RootQuery,
mutation: Mutation // 뮤테이션 추가가
})
// Express 서버 생성
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true
}));
app.listen(4000, () => {
console.log("server is running port 4000");
})
2. 쿼리 작성
쿼리는 서버에서 데이터를 용청하는 방법으로, 예를 들면, 사용자 정보를 요청하는 쿼리는 다음과 같습니다.
const users = [
{ id: '1', name: "John Doe", email: "abcd@abcd.com" },
{ id: '2', name: "Kanny" },
]
users라는 배열에 id와 이름을 설정하는 name과 email 주소를 만들어 줍니다.
3. 뮤테이션 작성
뮤테이션은 데이터를 수정하는 방법으로, 사용자를 추가하는 뮤테이션은 다음과 같습니다.
mutation {
addUser(name: "Alice") {
id
name
}
}
- addUser: 뮤테이션의 이름
- args: 뮤테이션에서 사용할 인자를 정의, 여기서는 name 인자를 사용해 새 사용자의 이름을 전달
- resolve: 실제로 데이터를 처리하는 함수, 새 사용자를 만들어 users 배열에 추가하고, 추가된 사용자 반환
GitHub - Koras02/graphql-b
Contribute to Koras02/graphql-b development by creating an account on GitHub.
github.com
LIST
'Back-End > GraphQL' 카테고리의 다른 글
[GraphQL] 1장. GraphQL의 탄생 (0) | 2025.02.10 |
---|