leonardomso / graphql-mongodb-server Goto Github PK
View Code? Open in Web Editor NEWA GraphQL MongoDB server.
A GraphQL MongoDB server.
I want to save in the database posts, that have a nested property, like this:
const post = {
title: 'some title',
body: 'some text',
date: {
published: '2019-06-28T10:00:00',
updated: '2019-06-29T11:00:00'
}
}
I try it like this:
1. /server/models/posts
const PostSchema = new Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
date: {
published: {
type: Date,
default: Date.now()
},
updated: {
type: Date,
default: Date.now()
}
}
});
2. /graphql/types/Post/index.js
export default `
type Dates {
published: String
updated: String
}
type Post {
_id: ID!
title: String!
body: String!
date: Dates
}
type Query {
post(_id: ID!): Post!
posts: [Post!]!
}
type Mutation {
createPost(post: CreatePostInput): Post!
updatePost(_id: ID!, post: UpdatePostInput): Post!
deletePost(_id: ID!): Post!
}
type Subscription {
post: PostSubscriptionPayload!
}
type PostSubscriptionPayload {
mutation: MutationType!
post: Post!
}
input CreatePostInput {
title: String!
body: String!
date: Dates
}
input UpdatePostInput {
title: String
body: String
date: Dates
}
enum MutationType {
CREATED
DELETED
UPDATED
}
`;
3. /graphql/resolvers/Post/index.js
import Post from "../../../server/models/Post";
export default {
Query: {
post: async (parent, { _id }, context, info) => {
return await Post.findOne({ _id }).exec();
},
posts: async (parent, args, context, info) => {
const res = await Post.find({})
.populate()
.exec();
return res.map(u => ({
_id: u._id.toString(),
title: u.title,
body: u.body,
date: u.date
}));
}
},
Mutation: {
createPost: async (parent, { post }, context, info) => {
const newPost = await new Post({
title: post.title,
body: post.body,
date: post.date
});
try {
const result = await new Promise((resolve, reject) => {
newPost.save((err, res) => {
err ? reject(err) : resolve(res);
});
});
return newPost;
} catch (error) {
console.log(error);
throw error;
}
},
updatePost: async (parent, { _id, post }, context, info) => {
return new Promise((resolve, reject) => {
Post.findByIdAndUpdate(_id, { $set: { ...post } }, { new: true }).exec(
(err, res) => {
err ? reject(err) : resolve(res);
}
);
});
},
deletePost: async (parent, { _id }, context, info) => {
try {
// searching for creator of the post and deleting it from the list
const post = await Post.findById(_id);
return new Promise((resolve, reject) => {
Post.findByIdAndDelete(_id).exec((err, res) => {
err ? reject(err) : resolve(res);
});
});
} catch (error) {
console.log(error);
throw error;
}
}
},
Subscription: {
post: {
subscribe: (parent, args, { pubsub }) => {
//return pubsub.asyncIterator(channel)
}
}
},
Post: {
}
};
When I test the createPost mutation, then I get the following error message:
The type of UpdatePostInput.date must be Input Type but got: Dates.
at assertValidSchema (C:\Workspace\Sites\react\graphql\node_modules\graphql\type\validate.js:71:11)
at Object.validate (C:\Workspace\Sites\react\graphql\node_modules\graphql\validation\validate.js:55:35)
at doRunQuery (C:\Workspace\Sites\react\graphql\node_modules\apollo-server-core\src\runQuery.ts:181:30)
at C:\Workspace\Sites\react\graphql\node_modules\apollo-server-core\src\runQuery.ts:80:39
at process._tickCallback (internal/process/next_tick.js:68:7)
Error: The type of CreatePostInput.date must be Input Type but got: Dates.
Hey man, thanks for the awesome thing you've built!
I got your server running and connected, but when I create a Post it's not added to the User's array of posts.
What was your solution to it?
I'm trying to add on my logic on top and if I get it working I'll create a pull request.
Cheers 💪
Probably time to update your dependencies
I followed the directions in the readme.md. The following query returns the following error.
'''{
users {
id
}
}
'''
'''{
"errors": [
{
"message": "User is not defined",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"users"
]
}
],
"data": {
"users": null
}
}'''
After installing and starting the server:
npm start
> [email protected] start C:\Workspace\Sites\react\graphql-mongodb-server
> npm run server
> [email protected] server C:\Workspace\Sites\react\graphql-mongodb-server
> nodemon --exec babel-node server/index.js
[nodemon] 1.18.10
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `babel-node server/index.js`
Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade caniuse-lite browserslist`
�� Server is running on http://localhost:4000
MongoDB connected
I receive the following error message at http://localhost:4000/playground:
Cannot GET /playground
If I change the URL e.g. to http://localhost:4000/graphql, then I get:
Cannot GET /graphql
In the console I see the following error messages:
Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”). users:1:1
Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff2;base64,d09GMgABAAAAADKgA… (“default-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff2;base64,d09GMgABAAAAADB4A… (“default-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff2;base64,d09GMgABAAAAABDIA… (“default-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff2;base64,d09GMgABAAAAABkIA… (“default-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff2;base64,d09GMgABAAAAABqsA… (“default-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff2;base64,d09GMgABAAAAABUkA… (“default-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff2;base64,d09GMgABAAAAAB4AA… (“default-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”). users:1:1
Content Security Policy: The page’s settings blocked the loading of a resource at eval (“default-src”).
Source map error: TypeError: NetworkError when attempting to fetch resource.
Resource URL: moz-extension://83088240-0f93-4b6a-9152-e32a2373f081/node_modules/webextension-polyfill/dist/browser-polyfill.js
Source Map URL: browser-polyfill.js.map[Learn More]
Source map error: TypeError: NetworkError when attempting to fetch resource.
Resource URL: moz-extension://8dd165e0-5819-47ef-98ca-542db01eafbb/content/js/purify.min.js
Source Map URL: purify.min.js.map[Learn More]```
I have a simple request like this:
query {Posts{_id title date {published}}}
How can I sort the posts e.g. by publishing date and limit the number of posts? And how can I filter the posts, e.g. that I get only posts older than some date?
I`m a new starter for express and graphql, thank you for this demo project.
I can create user,query user,users and update user, but I dont know how to create post with graphql.
Localhost:4000 show connection blocked too
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.