我创建了以下代码,以从graphql响应中返回title,forename和surname。我使用这些返回值进行自动测试以确定其值:
const { createApolloFetch } = require('apollo-fetch');
const uri = 'http://localhost:3000';
const query = `{
Post(id: 1) {
id
title
forename
surname
}
}
`;
const apolloFetch = createApolloFetch({ uri });
const returnApolloBody = () => {
return apolloFetch({query}).
then(res => res.data)
.catch(err => {
throw new Error(err);
});
};
const responseForename = returnApolloBody().then(result => result.Post.forename);
const responseTitle = returnApolloBody().then(result => result.Post.title);
const responeSurname = returnApolloBody().then(result => result.Post.surname);
module.exports = {
responseForename: responseForename,
responseTitle: responseTitle,
responeSurname: responeSurname,
};
但是我意识到这不是最有效的方式,因为我正在为每个值发出单独的http请求。我认为将整个响应存储为JSON值会更容易,然后从这个变量中提取值,但是我没有太多运气。我有以下代码,值返回为undefined:
const { createApolloFetch } = require('apollo-fetch');
const uri = 'http://localhost:3000';
const query = `{
Post(id: 1) {
id
title
forename
surname
}
}
`;
const apolloFetch = createApolloFetch({ uri });
const returnApolloBody = () => {
return apolloFetch({query}).
then(res => res)
.catch(err => {
throw new Error(err);
});
};
const response = returnApolloBody().then(response => response);
const forename = response.then(response => response.Post.forename);
const surname = response.then(response => response.Post.surname);
const title = response.then(response => response.Post.title);
module.exports = {
forename: forename,
title: title,
surname: surname
};
我缺少什么才能让我将整个响应存储在const中,然后查询该const中的特定属性?
提前致谢
答案 0 :(得分:0)
您应该能够将结果response.Post
作为对象返回,例如下面我使用apolloclient来获取用户个人资料
apolloclient.query({
query: q_my_profile}).then(
resp => {
resolve(resp.data.my_profile);
},
error => {
reject(error.message);
});