简体   繁体   中英

how to have mutliple different instances of the same type in mock data

I have simple schema and server; Schema.js:

const typeDefs = gql`
  type Query {
    people: [Person!]!
  }

  type Person {
    name: String!
    age: Int!
    job: String
  }
`;

And my server:

const mocks = {
  Person: () => ({
    name: () => "Henry Adams", 
    age: () => 21,
  })

};

const server = new ApolloServer({ typeDefs, mocks: mocks });

server.listen().then(() => {
  console.log(`
     Listening on port 4000
     Query at http://localhost:4000
      `);
});

The above works as expected when I query for it on graphIQL, I know how to have multiple of the same exact instance if I change the server.js to the following:

const mocks = {
 Query: () => ({
    people: () => [...new Array(4)],
  }),
  Person: () => ({
    name: () => "Henry Adams", 
    age: () => 21,
  })

};

const server = new ApolloServer({ typeDefs, mocks: mocks });

server.listen().then(() => {
  console.log(`
     Listening on port 4000
     Query at http://localhost:4000
      `);
});

This however is NOT what I am looking to do, instead I would like to do multiple different instances of the same type in my mock data, I have tried two different syntaxes and suprisingly cannot find this by googling: Syntax one:

const mocks = {
  Person: () => ({
    name: () => "Henry Adams", 
    age: () => 21,
  }),

Person: () => ({
    name: () => "Berry, Lee", 
    age: () => 28,
  })

};

When I query with the above syntax only the second instance "Berry Lee" comes up. The second syntax I assumed would work:

const mocks = {
  Person: () => ({
    name: () => "Henry Adams", 
    age: () => 21,
  }, 
   {
    name: () => "Berry, Lee", 
    age: () => 28,
  }),

};

I have the same problem with this second syntax, only the second type shows up when querying.

I got the original code from following the apollo odyssey tutorials 1 and 2 on the apollo graphql site but doing some further digging I found another post that brought my attention to rootValue: root and one work around I have found for the original code is the following (with the same schema as original post):

const mocks= [
  {
    name: "Henry Adams",
    age: 21,
  },
  {
    name: "Benny Lee",
    age: 29,
  },
];

const root = {
  people: () => mocks,
};

const server = new ApolloServer({ typeDefs, rootValue: root });

I am not sure if there is a way to do this using mocks: true or mocks: mocks yet so I will leave this question unanswered for some time for a possible more elaborate answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM