简体   繁体   中英

How to create nested connection in prisma query?

I'm having issues getting the prisma/graphql-yoga client to work as I expect.

I'm trying to create mutation query that creates a connection between two nodes ( Game and User ), but the mutation is not behaving as I expect it to.

Here's the system I'm on:

node --version
v11.6.0

package.json

{
  "dependencies": {
    "graphql-yoga": "^1.17.0",
    "prisma-client-lib": "^1.25.3"
  },
  ...
}

docker-compose.yml

version: '3'
services:
  prisma:
    image: prismagraphql/prisma:1.25
    restart: always
    ports:
    - "4466:4466"
    environment:
      PRISMA_CONFIG: |
        port: 4466
        databases:
          default:
            connector: postgres
            host: postgres
            port: 5432
            user: prisma
            password: prisma
            migrations: true
  postgres:
    image: postgres:10.5
    restart: always
    environment:
      POSTGRES_USER: prisma
      POSTGRES_PASSWORD: prisma
    volumes:
      - postgres:/var/lib/postgresql/data
volumes:
  postgres:

Here is the datamodel.prisma file:

type Game {
  id: ID! @unique
  createdAt: DateTime!
  updatedAt: DateTime!
  board: String
  playerOne: User
}

type User {
  id: ID! @unique
  createdAt: DateTime!
  wins: Int
}

Here is the mutation I send:

mutation {
  createGame(userId: "cjraz4ogb000s0894lbrugksi") {
    id
    board
    playerOne {
      id
    }
  }
}

Here is the resolver:

async function createGame(parent, args, context, info) {
  const game = await context.prisma.createGame({
    playerOne: { connect: { id: args.userId } },
    board: "[[]]"
  })
  return game
}

As you can see in the response, the resolver creates a Game object but there is no user associated with this game. Shown below is the response from the GraphQL playground mutation:

{
  "data": {
    "createGame": {
      "id": "cjraz8iwr001e08940ok9luki",
      "board": "[[]]",
      "playerOne": null
    }
  }
}

The response I expect would look something like this:

{
  "data": {
    "createGame": {
      "id": "cjraz8iwr001e08940ok9luki",
      "board": "[[]]",
      "playerOne": {
        id: "cjraz8iwr001e08940ok9luki" <- id from above
      }
    }
  }
}

Solution

Just as @Errorname mentioned, I needed to implement the resolver function for the playerOne relation. Adding the lines of code below solved the issue.

function playerOne(parent, args, context, info) {
  return context.prisma.game({ id: parent.id }).playerOne()
}

Because you are using prisma-client , you must write the resolver for the connection ( Documentation ):

Game: {
  playerOne: (root, args, ctx) => ctx.prisma.game({id: root.id}).playerOne()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM