Search code examples
graphqlprismaprisma-graphql

Do I have to create a new type to define array of objects in GraphQL schemas?


I’m trying to replicate a REST API that I’ve built in the past and one part that got me thinking was if one of my tables had an array of objects. So for example, I have a table called Profile and it contains arrays Experience and Education that would strictly be under Profile but has its own fields as well but not its own table.

While I was adding fields in GraphQL, I bumped into this not really having a solid solution other than to create new types and then associating them with relationships and then have a resolver or a front-end make sure a Profile is created first before the Experience/Education portion is. I’m not sure if it’s the right way to do it or if there is a better way to do it. Down below is a snippet of what I ended up using… looking at the admin page, there are created tables for Profile, Experience and Education which is expected. But is there a way to only have just Profile and accomplish something similar? Or is this more of a way of life with GraphQL?

type Profile {
    id: ID! @id
    handle: String!
    company: String
    website: String
    location: String
    status: String!
    githubUsername: String
    experience: [Experience!] @relation(link: INLINE)
    education: [Education!] @relation(link: INLINE)
}

type Experience {
  id: ID! @id
  title: String!
  company: String!
}

type Education {
  id: ID! @id
  title: String!
  company: String!
}


Solution

  • In Prisma, you can use embedded types. You would drop the @relation directive and add @embedded directives to the types you're embedding:

    type Profile {
        id: ID! @id
        handle: String!
        company: String
        website: String
        location: String
        status: String!
        githubUsername: String
        experience: [Experience!]
        education: [Education!]
    }
    
    type Experience @embedded {
      title: String!
      company: String!
    }
    
    type Education @embedded {
      title: String!
      company: String!
    }
    

    However, this only possible if you're using MongoDB for your database and there's some specific limitations listed in the docs when using embedded types.