3 votes
160 views
by Nikolas Burk

Introduction

In this quickstart tutorial, you'll learn how to build a GraphQL server with Node.JS. You will use graphql-yoga as your web server. The server is connected to a Prisma database API using prisma-binding.

To learn more about the core concepts of GraphQL server development with Prisma and the architecture, read the corresponding Introduction chapters.

The code for this project can be found as a GraphQL boilerplate project on GitHub.

Install required command line tools

Throughout the course of this tutorial, you'll use the Prisma CLI to create and manage your Prisma database API. You'll also use the GraphQL CLI for certain workflows around your GraphQL server.

Step 1

Open your terminal and globally install both CLIs via npm:

npm install -g prisma graphql-cli

Bootstrap your GraphQL server

You'll now bootstrap the code for your GraphQL server using the graphql create command from the GraphQL CLI.

Step 2

Open your terminal and run the following command:

graphql create my-app --boilerplate node-basic

You're passing two arguments to the command:

  • my-app: This is the directory name where the CLI is going to put all files for your project.
  • --boilerplate node-basic: This specifies which GraphQL boilerplate you want to use as a starter kit for your GraphQL server.

After graphql create has finished, your Prisma database API is deployed and will be accessible under the endpoint that's specified in /my-app/database/prisma.yml.

Note that the endpoint is also referenced in src/index.js. There, it is used to instantiate Prisma in order to create a GraphQL binding from the application schema and the Prisma database schema (think of the binding as a "GraphQL ORM" layer):

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context: req => ({
    ...req,
    db: new Prisma({
      typeDefs: 'src/generated/prisma.graphql', // the auto-generated GraphQL schema of the Prisma API
      endpoint: '__PRISMA_ENDPOINT__',          // the endpoint of the Prisma API
      debug: true,                              // log all GraphQL queries & mutations sent to the Prisma API
      // secret: 'mysecret123',                 // only needed if specified in `database/prisma.yml`
    }),
  }),
})

Here's the file structure of the project:

Let's investigate the generated files and understand their roles:

  • / (root directory)

  • /database

  • /src

    • src/schema.graphql defines your application schema. It contains the GraphQL API that you want to expose to your client applications.
    • src/generated/prisma.graphql defines the Prisma schema. It contains the definition of the CRUD API for the types in your data model and is generated based on your datamodel.graphql. You should never edit this file manually, but introduce changes only by altering datamodel.graphql and run prisma deploy.
    • src/index.js is the entry point of your server, pulling everything together and starting the GraphQLServer from graphql-yoga.

Most important for you at this point are database/datamodel.graphql and src/schema.graphql. database/datamodel.graphql is used to define your data model. This data model is the foundation for the API that's defined in src/schema.graphql and exposed to your client applications.

Here is what the data model looks like:

type Post {
  id: ID! @unique
  isPublished: Boolean! @default(value: "false")
  title: String!
  text: String!
}

Based on this data model Prisma generates the Prisma database schema, a GraphQL schema that defines a CRUD API for the types in your data model. This schema is stored in src/generated/prisma.graphql and will be updated by the CLI every time you deploy changes to your data model.

You're now set to start the server! 🚀

Start the server

Step 1

Invoke the dev script that's defined in package.json. It will start the server and open a GraphQL Playground for you.

cd my-app
yarn dev

Note that the Playground let's you interact with two GraphQL APIs side-by-side:

  • app: The web server's GraphQL API defined in the application schema (from ./server/src/schema.graphql)
  • database: The CRUD GraphQL API of the Prisma database API defined in the Prisma schema (from ./server/src/generated/prisma.graphql)

Note that each Playground comes with auto-generated documentation which displays all GraphQL operations (i.e. queries, mutations as well as subscriptions) you can send to its API. The documentation is located on the rightmost edge of the Playground.

Once the Playground opened, you can send queries and mutations.

Sending queries and mutations against the application schema

The GraphQL API defined by your application schema (src/schema.graphql) can be accessed using the app Playground.

Step 2

Paste the following mutation into the left pane of the app Playground and hit the Play-button (or use the keyboard shortcut CMD+Enter):

mutation {
  createDraft(
    title: "GraphQL is awesome!",
    text: "It really is."
  ) {
    id
  }
}

If you now send the feed query, the server will still return an empty list. That's because feed only returns Post nodes where isPublished is set to true (which is not the case for Post nodes that were created using the createDraft mutation). You can publish a Post by calling the publish mutation for it.

Step 3

Copy the id of the Post node that was returned by the createDraft mutation and use it to replace the __POST_ID__ placeholder in the following mutation:

mutation {
  publish(id: "__POST_ID__") {
    id
    isPublished
  }
}
Step 4

Now you can finally send the feed query and the published Post will be returned:

query {
  feed {
    id
    title
    text
  }
}

Sending queries and mutations against the Prisma database API

The GraphQL CRUD API defined by the Prisma schema (/src/generated/prisma.graphql) can be accessed using the database Playground.

As you're now running directly against the database API, you're not limited to the operations from the application schema any more. Instead, you can take advantage of full CRUD capabilities to directly create a published Post node.

Step 5

Paste the following mutation into the left pane of the database Playground and hit the Play-button (or use the keyboard shortcut CMD+Enter):

mutation {
  createPost(
    data: {
      title: "What I love most about GraphQL",
      text: "That it is declarative.",
      isPublished: true
    }
  ) {
    id
  }
}

The Post node that was created from this mutation will already be returned by the feed query from the application schema since it has the isPublished field set to true.

In the database Playground, you can also send mutations to update and delete existing posts. In order to do so, you must know their ids.

Step 6

Send the following query in the database Playground:

{
  posts {
    id
    title
  }
}
Step 7

From the returned Post nodes, copy the id of the one that you just created (where the title was What I love most about GraphQL) and use it to replace the __POST_ID__ placeholder in the following mutation:

mutation {
  updatePost(
    where: { id: "__POST_ID__" },
    data: { text: "The awesome community." }
  ) {
    id
    title
    text
  }
}

With this mutation, you're updating the text from That it is declarative. to The awesome community..

Step 8

Finally, to delete a Post node, you can send the following mutation (where again __POST_ID__ needs to be replaced with the actual id of a Post node):

mutation {
  deletePost(
    where: { id: "__POST_ID__" }
  ) {
    id
    title
    text
  }
}

Next steps

  • In this quickstart tutorial, you learned how to get started building a GraphQL server using Node.JS with Prisma as a "GraphQL ORM" layer. If you want to learn about how the Prisma database layer actually works, you can check out this tutorial in our docs.
  • Learn how to deploy the GraphQL server with Zeit Now or Apex Up.
  • Learn how to build a fully-fledged GraphQL server with authentication, pagination, filters and realtime subscriptions in this in-depth Node & GraphQL tutorial on How to GraphQL.