首页 > 解决方案 > GraphQL: Creating and Returning an Object in a Resolver?

问题描述

I've got a mutation resolver that I call directly from the server like this:

import {graphql} from "graphql";
import {CRON_JOB_TO_FIND_USERS_WHO_HAVE_GONE_OFFLINE_MUTATION} from "../../query-library";
import AllResolvers from "../../resolvers";
import AllSchema from "../../schema";
import {makeExecutableSchema} from "graphql-tools";

const typeDefs = [AllSchema];
const resolvers = [AllResolvers];

const schema = makeExecutableSchema({
    typeDefs,
    resolvers
});

const {data, errors} = await graphql(
    schema,
    CRON_JOB_TO_FIND_USERS_WHO_HAVE_GONE_OFFLINE_MUTATION,
    {},
    {caller: 'synced-cron'},
    {timeStarted: new Date().toISOString().slice(0, 19).replace('T', ' ')}
)

The mutation resolver is called and runs correctly. I don't need it to return anything, but GraphQL throws a warning if it doesn't, so I'd like it to return an object, any object.

So I'm trying it like this:

SCHEMA

cronJobToFindUsersWhoHaveGoneOffline(timeStarted: String): myUserData

QUERY

// note -- no gql. This string is passed directly to function graphql() 
// where it gets gql applied to it.
const CRON_JOB_TO_FIND_USERS_WHO_HAVE_GONE_OFFLINE_MUTATION = `
    mutation ($timeStarted: String){
        cronJobToFindUsersWhoHaveGoneOffline(timeStarted: $timeStarted){
                id,
        },
    }
`;

RESOLVER

cronJobToFindUsersWhoHaveGoneOffline(parent, args, context) {
    return Promise.resolve()
        .then(() => {
            // there is code here that finds users who went offline if any
            return usersWhoWentOffline;
        })
        .then((usersWhoWentOffline) => {
            // HERE'S WHERE I HAVE TO RETURN SOMETHING FROM THE RESOLVER

            let myUserDataPrototype = {
                __typename: 'myUserData',
                id: 'not_a_real_id'
            }
            const dataToReturn = Object.create(myUserDataPrototype);
            dataToReturn.__typename = 'myUserData';
            dataToReturn.id = 'not_a_real_id';

            return dataToReturn; <==GRAPHQL IS NOT HAPPY HERE
        })
        .catch((err) => {
            console.log(err);
        });
},
}

GraphQL throws this warning:

data [Object: null prototype] {

cronJobToFindUsersWhoHaveGoneOffline: [Object: null prototype] { id: 'not_a_real_id' } }

errors undefined

I have tried all kinds of different ways to fix this, but I haven't figured out the correct syntax yet.

What is a good way to handle this?

标签: node.jsgraphqljavascript-objects

解决方案


这似乎不是一个警告。看起来您正在将结果写入某个地方的控制台。


推荐阅读