const post = {
title: 'some title',
body: 'some text',
date: {
published: '2019-06-28T10:00:00',
updated: '2019-06-29T11:00:00'
}
}
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()
}
}
});
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
}
`;
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: {
}
};