可以在GraphQL中使用Resolvers来模拟数据源而不依赖数据库。
举例来说,我们可以使用一个数组来表示数据。在Resolvers中定义一个查询类型,并返回这个数组。
const { graphql, buildSchema } = require('graphql');
// 定义一个数组来表示数据
const books = [
{ id: 1, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' },
{ id: 3, title: 'Pride and Prejudice', author: 'Jane Austen' },
];
// 定义一个Schema
const schema = buildSchema(`
type Query {
books: [Book]!
}
type Book {
id: ID!
title: String!
author: String!
}
`);
// 定义Resolvers
const resolvers = {
Query: {
books: () => books,
},
};
// 执行查询
graphql(schema, '{ books { id, title, author } }', resolvers)
.then(response => console.log(response))
.catch(error => console.error(error));
在这个示例中,我们在Resolvers中定义了一个查询类型,它返回一个表示书籍的数组。在执行查询时,我们可以看到返回的数据与数组中的数据一致。