🐶
ApolloServerでGraphQLServerを構築する。
ApolloServerを利用してGraphQLのサーバを作成する事が目的です。
成果物
Hanads-on
ディレクトリ構成
~/develop/graphql/gql_server $ tree -I node_modules
.
├── package.json
├── server.js
└── yarn.lock
0 directories, 3 files
package.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"apollo-server": "^3.10.1",
"graphql": "^16.6.0"
},
"dependencies": {
"gql": "^1.1.2"
}
}
server.js
const { ApolloServer, gql } = require('apollo-server');
const users = [
{
id: 1,
name: 'kouji',
email: 'kouji@gmail.com',
age: 20,
},
{
id: 2,
name: 'takashi',
email: 'takashi@gmail.com',
age: 19,
},
];
const typeDefs = gql`
type User {
name: String
email: String
}
type Query {
user: [User]
}
`;
const resolvers = {
Query: {
user: () => users,
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Server reday at ${url}`);
});
→localhost:4000で実行!!すると、Apolloserverが起動する!!
GraphQLのクエリ
query ExampleQuery {
user {
name
email
}
}
Discussion