0

I'm using react + graphql with apollo client in my frontend and graphene + python for the backend

I have a mutation to update or add a new course like described below:

import { gql } from "@apollo/client";

const ADD_OR_UPDATE_COURSE = gql`
    mutation AddCourse($id: ID, $description: String, $name: String!, $orgId: ID!){
        addCourse(id: $id,description: $description, name: $name, orgId: $orgId)
        {
            course {
                id
                name
                description
            }
        }
    }`;

export default ADD_OR_UPDATE_COURSE;

This is fine for adding a single course, but I'd like to be able to add multiple courses without having to send a new request to backend multiple times.

The answer by Daniel in this post and the one by marktani in this other post almost give me what I need, except that I would like this to be dynamic, without knowing before hand how many insertions will be.

It has been awhile since their posts, so I was wondering if today there's an easy solution to this, or should I just to ahead and modify my backend side for a mutation that accepts a list instead of single course?

Rafael Santos
  • 293
  • 3
  • 18

1 Answers1

2

You need to update your backend to accomodate a list input because graphql is strongly typed. So, either you do multiple aliased mutations or make it so that your input accepts a list of courses. Either way, you have to follow what's defined in the schema.

You can try something like this:

class CourseInput(InputObjectType):
    name = graphene.String()
    orgId = graphene.Int()
    description = graphene.String()

class CreateCourses(graphene.Mutation):
    class Input:
       courses = graphene.List(CourseInput)

    courses = graphene.List(lambda: Course)

    def mutate(self, root, info, **kwargs):
        errors = []
        for course in kwargs.get('courses'):
            try:
                Course.objects.create(**course)
            except:
                errors.append(f'can't create ${course.name}')
        return CreateCourses(courses=courses, errors=errors)

As an aside, shouldn't your app generate the id for the course instead of people putting it in?

Jerven Clark
  • 1,191
  • 2
  • 13
  • 26
  • hey thanks for the comment. In the end that's exactly what I did. And yes, the ids are auto generated. In the case of the code I provided that is because in the implementation for the single course I have both update and add action wrapped together in the same mutation, so if an user provides an id, it is an update, otherwise if id is "" it's an insert :) – Rafael Santos Jul 17 '21 at 17:28