Reputation: 11661
I have nodejs and graphql application.
My User Schema and resolver using 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...
});
I add resolver to my 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 }
},
});
I need to return { token, user } for this resolver.
What type should I defined?
This I try but failed:
type: { token: 'String', user: UserTC.getType() }
Upvotes: 3
Views: 973
Reputation: 1
I don't know if you already solved the question, but this way you can define what you will use as Args and what fields can be Exposed in the resolver
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);
Here's an example using 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
});
});
}
});
Now you need to call the resolver somewhere like this login: UserTC.getResolver('Auth')
Upvotes: 0