๋ฐ์ํ
๋ชฉ์ฐจ
- Introduction
- Apollo with express
- Connect mongo db
- Conclusion
๐ Introduction
์๋ ํ์ธ์. ์ค๋์ Apollo๋ฅผ ์ด๋ป๊ฒ ์ฐ๋ํ๋์ง์ ๋ํด์ ํ๋ฒ ์์๋ณผ๊ฒ์. ํด๋น ์์ ์ฝ๋๋ ์ฌ๊ธฐ์ ํ์ธ ํ ์ ์์ต๋๋ค.
๐ Apollo with express
Apollo์์ ๊ฐ์ฅ ์ค์ํ๊ฑด typeDefs์ resolvers์ ๋๋ค.
import express from "express";
import { ApolloServer, gql } from "apollo-server-express";
const app = express();
// typeDefs๋ก ์คํค๋ง๋ฅผ ์ค์ ํด์ค์ ์์ด์.
const typeDefs = gql`
type Query {
hello: String!
}
`;
// resolvers๋ก๋ ์ค์ ๋ก ์ด๋ป๊ฒ query๋ฅผ ์ค์ง ์๋ ค์ฃผ๊ฒ ๋ฉ๋๋ค.
const resolvers = {
Query: {
hello: () => "hello",
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.applyMiddleware({ app });
app.use((req, res) => {
res.status(200);
res.send("Hello!");
res.end();
});
app.listen({ port: 4000 }, () =>
console.log(`๐ Server ready at http://localhost:4000${server.graphqlPath}`)
);
๐ Connect Mongo DB
๊ฐ๋จํ๊ฒ ์ผ๋จ Cat์ด๋ผ๋ ๋ชจ๋ธ์ ํ๋ฒ ๋ง๋ค์ด ๋ณผ๊ฒ์.
import mongoose from "mongoose";
export const Cat = mongoose.model("Cat", { name: String });
๊ทธ๋ฆฌ๊ณ ์ด์ typeDefs๋ฅผ ์ค์ ํด์ค๋๋ค. query์ mutation์ ๋ง๋ค์ด ๋ณผ๊ฒ์.
import { gql } from "apollo-server-express";
export const typeDefs = gql`
type Query {
hello: String!
cats: [Cat!]!
}
type Cat {
id: ID!
name: String!
}
type Mutation {
createCat(name: String!): Cat!
}
`;
์ด์ ๋ง๋ typeDefs๋ฅผ ์ค์ ๋ก ์ด๋ป๊ฒ ํ ์ง ๋ณด์ฌ์ฃผ๋ resolver๋ฅผ ์์ฑํฉ๋๋ค.
import { Cat } from "./models/Cat";
export const resolvers = {
Query: {
hello: () => "hello",
cats: () => Cat.find(),
},
Mutation: {
createCat: async (_, { name }) => {
const kitty = new Cat({ name });
await kitty.save();
return kitty;
},
},
};
graphql playground์์๋ ์ด๋ ๊ฒ ์์ฑํด์ค์ ์์ต๋๋ค.
cats:
query {
cats: {
name
}
}
createCat
mutation {
cretaeCat(name: "bob") {
id
name
}
}
๐ Conclusion
์ด๋ ๊ฒ ํ๋ฒ ๊ฐ๋จํ๊ฒ apollo๋ก server๋ฅผ ๋ง๋ค์ด ๋ณด์์ต๋๋ค. ๊ทธ๋ผ ๋ค์ ์๊ฐ์๋ vue3์์ ์ด๋ป๊ฒ apollo๋ฅผ ์ฐ๋ํ๋์ง์ ๋ํด์ ์์๋ณด๊ฒ ์ต๋๋ค.
๋ฐ์ํ
'Graphql_Apollo' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ํํ graphql & apollo ๊ฐ์ข - Apollo ์๋ฒ ๊ตฌ์ถ (0) | 2021.06.28 |
---|---|
Apollo - vue3์์ apollo ์ฌ์ฉํ๊ธฐ (0) | 2020.12.21 |