typescript 为什么GraphQL突变失败并出现400错误?

mitkmikd  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(174)

我的变体将useState变量作为参数,并将其传递给Mongoose API以保存在MongoDB上。我一直在尝试让此API工作,但由于某种原因,我总是得到POST http://localhost:4000/graphql 400 (Bad Request)错误。
我尝试在服务器端控制台记录变异输入变量,但代码从未到达解析器。
下面是我的代码:

前端/新帖子/页面. tsx

const ADD_POST = gql`
  mutation CreatePost($post: PostInput!) {
    createPost(post: $post) {
      post
    }
  }
`;

export default function page() {
  const [createPost, {data, loading, error}] = useMutation(ADD_POST)
  const [post, setPost] = useState<IPost>({
    contactInfo: {
      phone: "",
      email: "",
      sns: {
        type: "Twitter",
        username: ""
      }
    },
    title: "",
    description: "",
})

  const handleSubmit = async () => {
      //Send "/api/new-post" to process post variable
      const { data } = await axios.post("/api/new-post", { post: post });
      console.log("NewPost ", data)
      console.log("NewPost ", data.post)
      // Works up until here
      await createPost({variables: {post: data.post} })
      router.push('/')
    }catch(err: any){
      console.log(err.message)
    }
  };
  

       //sePost function, onChangeHandler and Inputs for each fields here...

    <button
      type="button"
      onClick={()=>handleSubmit()}>
        Click
    </button>

后端/源/后类型定义

export const postTypeDefs = `#graphql

  scalar JSON

  type Post {
    _id: ID!
    contactInfo: JSON
    title: String!
    description: String!
  }

  type Query {
    posts: [Post!]!
    }
    

  type CreatePostResponse {
    success: Boolean!
    error: String
  }

  type Mutation {
    createPost(post: PostInput): String
  }

  input PostInput {
    contactInfo: JSON
    title: String!
    description: String!
  }
`;

后端/解析器后. ts

const dateScalar = new GraphQLScalarType({

export const postResolvers = {
  JSON: GraphQLJSON,

  Query: {
    // Return all posts
    posts: async () => {
      try {
        await connectDB();
        const posts = await Post.find();
        return posts;
      } catch (err) {
        console.log(err);
      }
    },
   

    //Return posts by User's ObjectId
    postsByUserId: async (parent, args) => {
      const { postedBy } = args;
      await connectDB();
      const posts = await Post.find();
      return posts.filter((post) => post.postedBy.toString() === postedBy);
    }
  },

  Mutation: {
    createPost: async (parent, args)=>{
      try{
        const {post} = args;
        // Just want to make this console.log work
        console.log("API endpoint", post)
        //Add to Mongodb, logic follows...
        return { success: true };

      }catch(err){
        return { success: false, error: err.toString() };
      }
    }
  }

};

Mongoose 模式

import mongoose from 'mongoose';

const postSchema = new mongoose.Schema({
  contactInfo: {
    phone: { type: String, default: '' },
    email: { type: String, default: '' },
    sns: {
      type: {
        type: String,
        default: 'Twitter'
      },
      username: { type: String, default: '' }
    }
  },
  title: { type: String, required: true },
  description: { type: String, default: '' },

});

const Post = mongoose.model('Post', postSchema);

export default Post;
cwtwac6a

cwtwac6a1#

400错误的典型来源是GraphQL语法错误。该错误会在您的解析器被调用之前发生。请先在操场上尝试相同的查询以确保它工作正常。
我怀疑问题是您已经定义了CreatePost模式来返回String,但是您在变异结果中包含了一个字段。

createPost(post: $post) {
  post
}

createPost(post: $post)

此外,解析器逻辑(永远不会到达)试图返回对象return { success: true };而不是字符串,因此接下来将失败。

相关问题