2. type npm init -y
3. type npm install graphql-yoga
4. create index.js in server
5. install mongoDB, start mongod.exe
6 type npm install mongoose
7. type node index.js
8. web browser go to localhost:4000
display
left graphQL, right mongo compass
{
profiles{
id,
name,
amount,
category,
date
}
}
---------------------------------------------------------------------------
create
create new profile sam
createProfile(name: "sam", category: 1,
amount: 50.3){
id,
name,
amount,
date,
category
}
}
--------------------------------------------------------------------------
update
update amount of sam to 88888
mutation{
updateProfile(
id:"5b3d9ac7e2cf8334843741f2",
amount:888888
)
}
----------------------------------------------------------------------
delete
sam is removed
mutation{
removeProfile(id:"5b3d9ac7e2cf8334843741f2")
}
//index.js
const { GraphQLServer } = require('graphql-yoga');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db1');
const transactionSchema = mongoose.Schema({
name: String,
amount: Number,
category: Number,
date: String,
});
const transactionModel = mongoose.model('transactionModel', transactionSchema);
const typeDefs = `
type Query {
hello(name: String): String!
profiles: [transactionModel]
}
type transactionModel{
id: ID!
name: String!
amount: Float!
category: Int
date: String
}
type Mutation{
createProfile(name: String!, amount: Float, category: Int): transactionModel
updateProfile(id:ID!, name: String!, category: Int, amount: Float) : Boolean
removeProfile(id:ID!): Boolean
}
`
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}`,
profiles: ()=> transactionModel.find()
},
Mutation: {
createProfile: async (_, { name, amount, category }) => {
const transctionTime = new Date();
const profile = new transactionModel({
name: name,
amount: amount || 0,
category: category || 0,
date: transctionTime.toLocaleString(),
});
await profile.save();
return profile;
},
updateProfile: async (_, { id, name, category, amount }) => {
const transctionTime = new Date();
await transactionModel.findByIdAndUpdate(id,
{
name: name,
amount: amount,
category: category,
});
return true;
},
removeProfile: async (_, { id }) => {
await transactionModel.findByIdAndRemove(id);
return true;
}
}
}
const server = new GraphQLServer({ typeDefs, resolvers });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
server.start(() => console.log('Server is running on localhost:4000'))
});
reference:
http://chuanshuoge2.blogspot.com/2018/06/react-mongodb.html
No comments:
Post a Comment