如何存储" apollo-fetch"变量中的graphql响应?

时间:2018-04-25 15:26:34

标签: node.js graphql apollo apollo-client

我创建了以下代码,以从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中的特定属性?

提前致谢

1 个答案:

答案 0 :(得分:0)

您应该能够将结果response.Post作为对象返回,例如下面我使用apolloclient来获取用户个人资料

apolloclient.query({
query: q_my_profile}).then(
resp => {
    resolve(resp.data.my_profile);
},
error => {
    reject(error.message);
});