如何从GraphQL的解析器返回自定义对象?

时间:2019-05-14 20:44:38

标签: node.js graphql graphql-compose-mongoose graphql-compose

我有nodejs和graphql应用程序。

使用graphql-compose-mongoose的我的用户架构和解析器:

import { composeWithMongoose } from 'graphql-compose-mongoose';

const UserTC = composeWithMongoose(User, {
  fields: { remove: ['password'] },
});

UserTC.addResolver({
  name: 'currentUser',
  type: UserTC.getType(),
  resolve: currentUserResolver, // return user object...
});

我将解析器添加到我的UserTC:

UserTC.addResolver({
  name: 'login',
  args: {
    email: { type: 'String!' },
    password: { type: 'String!' },
  },
  type: /// <---- MISSING TYPE HERE
  resolve: async ({ args, context }) => {
    const { email, password } = args;
    const { token, user } = login({ email, password });
    return { token, user }
  },
});

我需要为此解析器返回{令牌,用户}。

我应该定义什么类型?

我尝试但失败了:

type: { token: 'String', user: UserTC.getType() }

1 个答案:

答案 0 :(得分:0)

我不知道您是否已经解决了这个问题,但是通过这种方式,您可以定义您将用作 Args 的内容以及可以在解析器中公开的字段

const { schemaComposer, toInputObjectType } = require('graphql-compose');

const MyCustomAuth = schemaComposer.createObjectTC({
    name: 'Login',
    fields: {
        // Args
        username: 'String!',
        password: 'String!',
        // Fields to return
        email: 'String',
        city: 'String',
        token: 'String'
    }
});

const MyCustomAuthITC = toInputObjectType(MyCustomAuth);

这是一个使用 JWT

的示例
UserTC.addResolver({
    kind: 'mutation',
    name: 'Auth',
    // Your Custom Object
    type: MyCustomAuth,
    args: {
        // Here goes the Input    
        input: MyCustomAuthITC
    },
    resolve: async ({args}) => {
        return new Promise( async (resolve, reject) => {
            const { username, password } = args.input;
            //Get user by username
            const user = await User.findOne({username});
            if (!user) reject('Authentication Failed');
            const token = jwt.sign(user.toJSON(), config.JWT_SECRET, {
                expiresIn: '1h',
                subject: user.id
            });            
            resolve({
                email: user.email,
                city: user.email,
                token: token
            });
        });
    }    
});

现在你需要像这样login: UserTC.getResolver('Auth')