In GraphQL Code First Approach I am trying to pass the same argumment for createUser
in createManyUser
but I want to pass it as an array to create many users at once. I searched a lot but couldn’t find it in GraphQL Code First Approach.
The Code
JavaScript
x
36
36
1
export const createUser = {
2
type: userType,
3
args: { // This work fine
4
email: { type: string },
5
username: { type: string },
6
firstName: { type: string },
7
lastName: { type: string }
8
},
9
resolve: async (_, args, { userAuth }) => {
10
try {
11
const user = await db.models.userModel.create(args);
12
return user;
13
} catch (error) {
14
throw Error(`${error.message}`)
15
}
16
}
17
}
18
19
export const createManyUser = {
20
type: new GraphQLList(userType),
21
args: [{ // Here I made an array [] but it dose not work so here is my problem
22
email: { type: string },
23
username: { type: string },
24
firstName: { type: string },
25
lastName: { type: string }
26
}],
27
resolve: async (_, args, { userAuth }) => {
28
try {
29
const user = await db.models.userModel.bulkCreate(args);
30
return user;
31
} catch (error) {
32
throw Error(`${error.message}`)
33
}
34
}
35
}
36
Advertisement
Answer
You can’t just put the args
options in an array, to tell GraphQL that you expect a list of things you explicitly need to construct a GraphQLList
type.
And you can’t make a mutation field take a list of named things either – you must give the mutation one named argument that expects a list of input objects. So it’ll be
JavaScript
1
22
22
1
export const createManyUser = {
2
type: new GraphQLList(userType),
3
args: {
4
inputs: { type: new GraphQLList(new GraphQLNonNull(new GraphQLInputObjectType({
5
// ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
6
name: 'CreateUserInput',
7
description: 'Input payload for creating user',
8
fields: {
9
email: { type: string },
10
username: { type: string },
11
firstName: { type: string },
12
lastName: { type: string }
13
}
14
})))
15
},
16
resolve: async (_, args, { userAuth }) => {
17
const user = await db.models.userModel.bulkCreate(args.inputs);
18
// ^^^^^^^
19
return user;
20
}
21
}
22
See also this article.