gpt4 book ai didi

javascript - GraphQL 查询返回错误 .filter 不是函数

转载 作者:行者123 更新时间:2023-12-03 00:32:33 25 4
gpt4 key购买 nike

我试图从 API 返回一些数据,这给我一条消息错误“userAPI.filter 不是函数”。该项目是使用 json 服务器设置的,我还有一个 db.js 文件,其中包含一个对象数组。我遇到的问题是让过滤器与 json 服务器一起工作。我已经测试过它,我可以毫无问题地从本地 .js 文件获取数据。我什至可以从 json 服务器获取数据以获取所有用户。

当我使用底部的过滤器时,它似乎不起作用。我有一种感觉,这与我用 axios 返回的数据有关,可能变量不是数组?但它可以让所有用户回来。我非常确定过滤器可以正常工作,因为它与文件中的测试 userAPI2 对象数组一起工作。

  const axios = require('axios');

const Query = {
greeting(parent, args, ctx, info) {
if(args.name) {
return `Hello ${args.name}!`
} else {
return 'Hello!'
}
},
avengers(parent, args, ctx, info) {
if(args.name) {
return `Your favourite character is ${args.name}`
} else {
return 'Avengers Assemble!'
}
},
hello(parent, args, ctx, info) {
return "Hello World"
},
me() {
return {
id: "abc123",
name: "John",
email: "example@gmail.com",
age: 32
}
},
users(parent, args, {db}, info) {
// Import from an external API server in this case json-server
const userAPI = axios.get('http://localhost:3004/users')
.then(response => {
return response.data
})

if (!args.query) {
// Import from local .js file
return db.users

// Import from an external API server in this case json-server
//return userAPI
}
// Import from local .js file
// return db.users.filter((user) => {
// return user.name.toLowerCase().includes(args.query.toLowerCase())
// })

const userAPI2 = [
{
id: '1',
name: 'User1',
email: 'user1@user1.com',
age: 32,
},
{
id: '2',
name: 'User2',
email: 'user2@user2.com',
age: 32,
},
{
id: '3',
name: 'User3',
email: 'user3@user3.com',
age: 32,
}
]

// Import from local .js file
// return db.users.filter((user) => {
// return user.name.toLowerCase().includes(args.query.toLowerCase())
// })

// Import from an external API server in this case json-server
return userAPI.filter((user) => {
return user.name.toLowerCase().includes(args.query.toLowerCase())
})
}
}

export {Query as default}

最佳答案

userAPI 变量包含调用 axios.get 的返回值。 Axios 请求方法(如 requestgetpost 等)返回一个将解析为响应对象的 Promise。响应对象本身包含数据,在本例中将是一个数组。

如果要过滤数据,则必须在解析器返回的 Promise 链中执行此操作,例如:

users(parent, args, {db}, info) {
return axios.get('http://localhost:3004/users')
.then(response => {
if (!args.query) {
return response.data
}
return response.data.filter((user) => {
return user.name.toLowerCase().includes(args.query.toLowerCase())
})
})
}

或者使用异步/等待:

users: async (parent, args, {db}, info) => {
const { data } = await axios.get('http://localhost:3004/users')
if (!args.query) {
return data
}
return data.filter((user) => {
return user.name.toLowerCase().includes(args.query.toLowerCase())
})
}

关于javascript - GraphQL 查询返回错误 .filter 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53794641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com