33
loading...
This website collects cookies to deliver better user experience
npm i -s apollo-server apollo-core express nodemon
nodemon help us to detect changes and automatically restart server for us.
//package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon ./index.js"
},
//users.js
const users =[
{
name:"Dev",
role: "DBA",
id:1
},
{
name:"Jhon Doe",
role: "Admin",
id:2
},
{
name:"Martin",
role: "Dev",
id:3
}
]
module.exports = users;
//index.js
const users =require("./users")
const express = require('express');
const { ApolloServerPluginLandingPageDisabled, ApolloServerPluginLandingPageGraphQLPlayground } = require('apollo-server-core');
const { ApolloServer, gql } = require('apollo-server-express');
const typDefs = gql`
type User{
name:String!,
role:String!,
id:Int
}
type Query{
getAll: [User!]!
}
type Mutation{
newUser(name :String!,role:String ,id:Int):User
}
`;
const resolvers = {
Query: {
getAll() {
return users;
}
},
Mutation: {
newUser(parent, args) {
const usr = args;
users.push(usr);
return usr;
}
}
}
const server = new ApolloServer({
typeDefs, resolvers,
plugins: [
ApolloServerPluginLandingPageGraphQLPlayground({
// options
})
, ApolloServerPluginLandingPageDisabled()
]
});
const app = express();
server.start().then(r => {
server.applyMiddleware({ app });
app.listen({ port: 3000 }, () =>
console.log('Now browse to http://localhost:4000' + server.graphqlPath)
)
})