Creating Data

Youtube video thumbnail

Now that our project is running locally with the Grafbase CLI, we've no data! Let's change that by using the playground to create some, locally.

Make sure to run npx grafbase dev!

Open the Playground by visiting http://localhost:4000.

Grafbase Playground

Grafbase automatically generates the mutations postCreate and commentCreate for the @models we defined in our schema.

We'll use postCreate to create our first Post! The postCreate mutation contains a single input argument that represents the shape of the data.

Both title and url are required.

mutation {
  postCreate(input: { title: "Grafbase", url: "https://grafbase.com" }) {
    post {
      id
    }
  }
}

You can see from the response that Grafbase successfully created a record, and assigned it an id.

But what happens if we try to create another Post with the same url? Because we set the url field as @unique, we'll get an error if you try to execute the same mutation:

{
  "data": null,
  "errors": [
    {
      "message": "The value https://grafbase.com is already taken on field \"url\"",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "postCreate"
      ]
    }
  ]
}

Feel free to add more unique Posts. Make sure to copy one or more of the Post ids, we'll need that next.

Grafbase provides the APIs to create and connect data. Let's now create a new Post and Comment together in the same mutation:

mutation {
  postCreate(
    input: {
      title: "Next.js"
      url: "https://nextjs.org"
      comments: [{ create: { message: "Next.js is awesome!" } }]
    }
  ) {
    post {
      id
      title
      comments(first: 1) {
        edges {
          node {
            message
          }
        }
      }
    }
  }
}

We can see from above that we can create both a new Post and Comment in the same mutation, but what if we wanted to create a new comment for an existing post?

Instead of using the postCreate mutation, we can instead use commentCreate and link the comment to our previous post.

mutation {
  commentCreate(
    input: {
      message: "I love GraphQL!"
      post: { link: "post_01GFQPA7DDCZ2WFZHQWP6NK9JQ" }
    }
  ) {
    comment {
      message
      post {
        title
      }
    }
  }
}

Playground Link Comment

Was this page helpful?