阿波罗服务器入门
λ yarn add --dev @babel/core @babel/cli @babel/preset-env
λ yarn add --dev nodemon // "start": "nodemon --exec babel-node index.js"
λ yarn add apollo-server graphql express
http://localhost:4000/?query={hello}
const { gql, ApolloServer } = require("apollo-server");
const _ = require("lodash");
const cats = [{ id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }];
const l = console.log;
const typeDefs = gql`
type Query {
cats: [Cat]
findCat(id: ID!): Cat
}
type Mutation {
addCat(cat: InputCat): Cat
changeCat(id: ID!, name: String): Cat
}
input InputCat {
name: String
}
type Cat {
id: String
name: String
}
`;
const resolvers = {
Query: {
cats: (parent, args, context, info) => {
return cats;
},
findCat(parent, args, context, info) {
const { id } = args;
return _.find(cats, { id: +id });
},
},
Mutation: {
addCat(parent, args, context, info) {
const { cat } = args;
cats.push({
...cat,
id: _.size(cats),
});
return _.last(cats);
},
changeCat(parent, args, context, info) {
l(args);
const { id, name } = args;
cats[_.findIndex(cats, ["id", +id])].name = name;
return _.find(cats, ["id", +id]);
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
get: http://localhost:4000/?query={cats { id name }}
get: http://localhost:4000/?query={ findCat(id: 1) { name } }