I'm stuck in a thunk function usage and I need to better understand how it works.
Code that DOES NOT WORK:
const fields = {
id: {
type: new GraphQLNonNull(GraphQLID),
resolve: (obj) => dbIdToNodeId(obj._id, "History")
},
timestamp: {
type: GraphQLLong
},
objectId: {
type: GraphQLString
},
user: {
type: require('../User/connections').default,
args: connectionArgs,
resolve: (source, args) => {
return UserModel.findOne({ id: source.id }).exec();
}
},
action: {
type: new GraphQLNonNull(GraphQLString)
}
};
export const HistoryType = new GraphQLObjectType({
name: 'History',
description: 'History',
interfaces: () => [NodeInterface],
isTypeOf: (value) => value instanceof HistoryModel,
fields: () => (fields)
});
Code that DOES WORK:
export const HistoryType = new GraphQLObjectType({
name: 'History',
description: 'History',
interfaces: () => [NodeInterface],
isTypeOf: (value) => value instanceof HistoryModel,
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLID),
resolve: (obj) => dbIdToNodeId(obj._id, "History")
},
timestamp: {
type: GraphQLLong
},
objectId: {
type: GraphQLString
},
user: {
type: require('../User/connections').default,
args: connectionArgs,
resolve: (source, args) => {
return UserModel.findOne({ id: source.id }).exec();
}
},
action: {
type: new GraphQLNonNull(GraphQLString)
}
})
});
From my "not very skilled on JavaScript thunks" point of view, both codes are the same, but they are not as only the second one works, so:
a) Why the codes does not behave the same ? Why storing the thunk content in a function (fields
) makes it behave differently ?
b) My fields
variable is used in the sequence of the code, so is there a way to make the thunk work keeping its object in a separate variable, as code 1 (in fact a fix for code 1 that keeps the field
variable) ?