이전포스팅에서 Prisma를 활용하여 GraphQL과 MySQL을 연동시켜보았고 ,,
터미널에서 MySQL에 직접 DB를 추가하고 Apollo Studio에서 Query요청에 제대로 응답하는 것을 확인했다..
이번에는 간단한 API를 작성하고 Prisma Studio에서 DB에 제대로 반영이 되는지 확인해봤다.
import { ApolloServer, gql } from "apollo-server";
import { PrismaClient } from "@prisma/client";
const client = new PrismaClient();
const typeDefs = gql`
type User {
id: Int!
user_name: String!
}
type Query {
User: [User]
}
type Mutation {
addUser(user_name: String): User
editUser(id: Int!, user_name: String): User
deleteUser(id: Int!): User
}
`;
const resolvers = {
Query: {
User: (_parent, _args, _context) => {
return client.User.findMany();
},
},
Mutation: {
addUser: (_parent, { user_name }, _context) => {
return client.User.create({ data: { user_name } });
},
editUser: (_parent, { id, user_name }, _context) => {
return client.User.update({ where: { id }, data: { user_name } });
},
deleteUser: (_parent, { id }, _context) => {
return client.User.delete({
where: { id },
});
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Running on ${url}`);
});
다음과 같이 Query 이외에도
User를 추가, 수정, 삭제하는 API를 작성했다..
Apollo Studio에서 제대로 작동하나 확인을 하면,,
현재 DB상태이다.
apollo studio에서 다음과 같이 mutation을 작성해주었다.
실행을 누르고 Query를 조회해보면
새로 5번이 생기고, 2번은 수정되었고, 4번은 삭제된 것을 확인할 수 있다.
prisma studio에서와 터미널에서 확인한 DB역시 모두 변경된 것을 확인할 수 있다.
이제 본격적으로 스키마 작성과 API작성을 해봐야겠다...
그래도 간단하겠지만...?
끝!