GraphQL嵌套结构Mutation问题:实现addEntity函数遇阻
Alright, let's tackle this nested data issue with your addEntity mutation. Since your queries are working fine, the problem is almost certainly in how you're defining your mutation schema or handling the nested primaryContact data in your resolver. Let's walk through the fixes step by step.
1. Fix Your Mutation Schema Definition
First, make sure you've properly defined input types for the nested data, and that your mutation accepts this structured input. Here's how to structure it correctly:
# Define the nested contact input type input PrimaryContactInput { name: String! email: String! phone: String # Optional field } # Define the main entity input type that includes the nested contact input EntityInput { name: String! description: String primaryContact: PrimaryContactInput! # Mark as required since you're including it } # Define the output types to match the data structure type PrimaryContact { name: String! email: String! phone: String } type Entity { id: ID! name: String! description: String primaryContact: PrimaryContact! } # Update your Mutation type to use the EntityInput type Mutation { addEntity(input: EntityInput!): Entity }
The key here is matching the input structure to the output structure so GraphQL knows how to validate and return the nested data.
2. Correct Your addEntity Resolver Logic
Next, ensure your resolver properly passes the nested data to json-server via axios. Json-server supports nested objects out of the box, so you don't need to do any special transformation—just send the full input object:
const axios = require('axios'); // Inside your resolvers object const resolvers = { // ... your existing query resolvers addEntity: async (parent, { input }) => { try { // Send the entire input (including nested primaryContact) to json-server const response = await axios.post('http://localhost:3000/entities', input); return response.data; } catch (error) { // Throw a clear error for debugging throw new Error(`Failed to create entity: ${error.response?.data || error.message}`); } } };
Double-check that your json-server endpoint is correct (adjust the URL if your server runs on a different port).
3. Validate Your GraphQL Server Setup
Make sure your express-graphql entry point correctly links your schema and resolvers. Here's a minimal working example:
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const resolvers = require('./resolvers'); // Import your resolvers // Build the schema using the definition from step 1 const schema = buildSchema(` input PrimaryContactInput { name: String! email: String! phone: String } input EntityInput { name: String! description: String primaryContact: PrimaryContactInput! } type PrimaryContact { name: String! email: String! phone: String } type Entity { id: ID! name: String! description: String primaryContact: PrimaryContact! } type Query { # Add your existing query resolvers here getEntity(id: ID!): Entity } type Mutation { addEntity(input: EntityInput!): Entity } `); const app = express(); app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: resolvers, graphiql: true, // Enable GraphiQL for easy testing })); app.listen(4000, () => { console.log('GraphQL server running at http://localhost:4000/graphql'); });
4. Troubleshoot Common Errors
If you're still seeing issues, check for these common pitfalls:
- Input/Output Type Mismatch: Ensure the fields in
PrimaryContactInputmatch exactly withPrimaryContact(e.g., don't mark a field as required in the output but optional in the input). - Json-Server Configuration: Make sure your
db.jsonhas an emptyentitiesarray to start with:{ "entities": [] } - Axios Headers: Axios automatically sets
Content-Type: application/json, but if you've overridden headers, double-check this is present. - Error Messages: Use the error details from GraphiQL—if it says "Field 'primaryContact' of type 'PrimaryContactInput!' must not be null", you're likely not passing the nested data correctly in your mutation test.
5. Test the Mutation in GraphiQL
Use this test mutation to verify everything works:
mutation AddNewEntity { addEntity(input: { name: "Acme Corp", description: "A test company", primaryContact: { name: "Jane Smith", email: "jane@acme.com", phone: "555-1234" } }) { id name primaryContact { name email } } }
If successful, you should get back the new entity with its nested primary contact data.
内容的提问来源于stack exchange,提问作者trueCodian

