瀏覽代碼

graphql mutations

Ivan Asmer 6 年之前
父節點
當前提交
f5188f8d2e
共有 1 個文件被更改,包括 42 次插入1 次删除
  1. 42 1
      index.js

+ 42 - 1
index.js

@@ -139,16 +139,24 @@ var schema = buildSchema(`
         comments(id: Int!): [Comment]
         subComments(id: Int!): [Comment]
     }
+    type Mutation {
+        createPost(title: String!, text: String!): Post
+        createComment(postID: Int!, text: String!): Post
+    }
+
     type Post {
         id: Int
         title: String
         text:  String
         age:   String
+        tagz:  [String]
         comments: [Comment]
+        timestamp: Int
     }
     type Comment {
         id: Int
         text:  String
+        age:   String
     }
 `);
 
@@ -157,6 +165,8 @@ async function getPost(args){
     //return Post.findById(id).then( post => (post.comments = post.getComments(), post) )
     let post = await Post.findById(id)
     post.comments = await post.getComments()
+    post.timestamp = post.createdAt.getTime()/1000
+    //console.log(post.createdAt, typeof post.createdAt, post.createdAt.getTime())
     return post;
 }
 
@@ -173,12 +183,25 @@ async function getSubComments(args){
     return comment.getComments()
 }
 
+async function createPost({title, text}){
+    return Post.create({title, text})
+}
+
+async function createComment({postID, text}){
+    let post    = await Post.findById(postID)
+    let comment = await Comment.create({text})
+    post.addComment(comment)
+    return comment
+}
+
 
 // Root resolver
 var root = {
     post: getPost,
     comments: getPostComments,
     subComments: getSubComments,
+    createPost,
+    createComment,
 };
 
 
@@ -193,9 +216,12 @@ app.use('/graphql', express_graphql({
 app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
 
 
+
+
 //query getPost($postID: Int!){
   //post(id:$postID){
     //text
+    //timestamp
   //}
 //}
 
@@ -207,9 +233,10 @@ app.listen(4000, () => console.log('Express GraphQL Server Now Running On localh
 
 //query getPostWithComments($postID: Int!){
   //post(id:$postID){
-    //text
+    //text	
     //comments {
       //text
+      //age
     //}
   //}
 //}
@@ -219,3 +246,17 @@ app.listen(4000, () => console.log('Express GraphQL Server Now Running On localh
     //text
   //}
 //}
+
+//mutation createPost($title: String!, $text:String!) {
+  //createPost(title: $title, text: $text) {
+     //title
+     //text
+  //}
+//}
+
+//mutation createComment($postID:Int!, $text:String!) {
+  //createComment(postID: $postID, text: $text) {     
+     //text
+  //}
+//}
+