--server folder
--package.json
--index.js
//set up mongoDB Altas, and find connection string for index.js
https://chuanshuoge2.blogspot.com/2018/07/mongodb-atlas-tutorial.html
//run node index.js
//access mongo Atlas via mongo Compass
Hostname: transactionpaper-taxad.mongodb.net
Username: viewer
Password: aaabbbccc
//mongo Compass displays data on the cloud/ mongo Atlas
---------------------------------------------------
//index.js
const { GraphQLServer } = require('graphql-yoga');
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://viewer:aaabbbccc@transactionpaper-taxad.mongodb.net/test?retryWrites=true');
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'))
});
---------------------------------------------
//package.json
{
"name": "react-mongo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@material-ui/core": "^1.3.1",
"apollo-boost": "^0.1.10",
"graphql": "^0.13.2",
"graphql-tag": "^2.9.2",
"graphql-yoga": "^1.14.10",
"mongoose": "^5.1.7",
"react-apollo": "^2.1.8",
"react-text-mask": "^5.4.2"
}
}
-------------------------
reference:
No comments:
Post a Comment