Skip to content

Latest commit

 

History

History
401 lines (319 loc) · 8.96 KB

README.md

File metadata and controls

401 lines (319 loc) · 8.96 KB

GraphQL Server Example

This example shows how to implement a GraphQL server with JavaScript (Node.js) based on Photon.js & graphql-yoga.

How to use

1. Download example & install dependencies

Clone the repository:

git clone [email protected]:prisma/photonjs.git

Install Node dependencies:

cd photonjs/examples/javascript/graphql
npm install

2. Install the Prisma 2 CLI

To run the example, you need the Prisma 2 CLI:

npm install -g prisma2

3. Set up database

For this example, you'll use a simple SQLite database. To set up your database, run:

prisma2 lift save --name 'init'
prisma2 lift up

You can now use the SQLite Browser to view and edit your data in the ./prisma/dev.db file that was created when you ran prisma2 lift up.

4. Generate Photon (type-safe database client)

Run the following command to generate Photon.js:

prisma2 generate

Now you can seed your database using the seed script from package.json:

npm run seed

5. Start the GraphQL server

Launch your GraphQL server with this command:

npm run start

Navigate to http://localhost:4000 in your browser to explore the API of your GraphQL server in a GraphQL Playground.

6. Using the GraphQL API

The schema that specifies the API operations of your GraphQL server is defined in ./src/schema.graphql. Below are a number of operations that you can send to the API using the GraphQL Playground.

Feel free to adjust any operation by adding or removing fields. The GraphQL Playground helps you with its auto-completion and query validation features.

Retrieve all published posts and their authors

query {
  feed {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}
See more API operations

Create a new user

mutation {
  signupUser(
    name: "Sarah"
    email: "[email protected]"
  ) {
    id
  }
}

Create a new draft

mutation {
  createDraft(
    title: "Join the Prisma Slack"
    content: "https://slack.prisma.io"
    authorEmail: "[email protected]"
  ) {
    id
    published
  }
}

Publish an existing draft

mutation {
  publish(id: "__POST_ID__") {
    id
    published
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Search for posts with a specific title or content

{
  filterPosts(searchString: "graphql") {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}

Retrieve a single post

{
  post(id: "__POST_ID__") {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Delete a post

mutation {
  deletePost(id: "__POST_ID__") {
    id
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

6. Evolving the example

If you want to change the GraphQL API, you need to adjust the GraphQL schema in ./src/schema.graphql and the respective resolver functions.

Adding an operation without updating the datamodel

To add new operation that can be based on the current datamodel, you first need to add the operation to the GraphQL schema's Query or Mutation type and then add the corresponding resolver function.

For example, to add a new mutation that updates a user's name, you can extend the Mutation type as follows:

type Mutation {
  signupUser(email: String!, name: String): User!
  createDraft(title: String!, content: String, authorEmail: String!): Post!
  deletePost(id: ID!): Post
  publish(id: ID!): Post
+ updateUserName(id: ID!, newName: String!): User
}

Then add the new resolver to the resolvers object in ./src/index.js:

const resolvers = {
  // ...
  Mutation: {
    // ...
+   updateUserName(parent, { id, newName }, context) {
+     return context.prisma.updateUser({
+       where: {
+         id
+       },
+       data: {
+         name: newName
+       }
+     })
+   }
  }
}

You can now send the following mutation to your GraphQL API:

mutation {
  updateUserName(
    id: "__USER_ID__"
    newName: "John")
  ) {
    id
    name
  }
}
Adding an operation and updating the datamodel

Some new API features can't be covered with the existing datamodel. For example, you might want to add comment feature to the API, so that users can leave comments on posts.

For that, you first need to adjust the Prisma datamodel in ./prisma/datamodel.prisma:

type User {
  id: ID! @id
  email: String! @unique
  name: String
  posts: [Post!]!
+ comments: [Comment!]!
}

type Post {
  id: ID! @id
  createdAt: DateTime!
  updatedAt: DateTime!
  published: Boolean! @default(value: "false")
  title: String!
  content: String
  author: User!
+ comments: [Comment!]!
}

+ type Comment {
+   id: ID! @id
+   text: String!
+   writtenBy: User!
+   post: Post!
+ }

After having updated the datamodel, you need to deploy the changes:

prisma deploy

Note that this also invokes prisma generate (because of the post-deploy hook in prisma.yml) which regenerates the Prisma client in ./src/generated/prisma-client.

To now enable users to add comments to posts, you need to add the Comment type as well as the corresponding operation to the GraphQL schema in ./src/schema.graphql:

type Query {
  # ... as before
}

type Mutation {
  signupUser(email: String!, name: String): User!
  createDraft(title: String!, content: String, authorEmail: String!): Post!
  deletePost(id: ID!): Post
  publish(id: ID!): Post
  updateUserName(id: ID!, newName: String!): User
+ writeComment(text: String!, postId: ID!, userId!: ID!): Comment
}

type User {
  id: ID!
  email: String!
  name: String
  posts: [Post!]!
+ comments: [Comment!]!
}

type Post {
  id: ID!
  createdAt: DateTime!
  updatedAt: DateTime!
  published: Boolean!
  title: String!
  content: String
  author: User!
+ comments: [Comment!]!
}

+ type Comment {
+   id: ID!
+   text: String!
+   writtenBy: User!
+   post: Post!
+ }

Next, you need to implement the resolver for the new operation in ./src/index.js:

const resolvers = {
  // ...
  Mutation: {
    // ...
+   writeComment(parent, { postId, userId}, context) {
+     return context.prisma.createComment({
+       text,
+       post: {
+         connect: { id: postId }
+       },
+       writtenBy: {
+         connect: { id: userId }
+       }
+     })
+   }
  }
}

Finally, because Comment has a relation to Post and User, you need to update the type resolvers as well so that the relation can be properly resolved (learn more about why this is necessary in this blog article):

const resolvers = {
  // ...
  User: {
    // ...
+   comments: ({ id }, args, context) {
+     return context.prisma.user({ id }).comments()
+   }
  },
  Post: {
    // ...
+   comments: ({ id }, args, context) {
+     return context.prisma.post({ id }).comments()
+   }
  },
+ Comment: {
+   writtenBy: ({ id }, args, context) {
+     return context.prisma.comment({ id }).writtenBy()
+   },
+   post: ({ id }, args, context) {
+     return context.prisma.comment({ id }).post()
+   },
+ }
}

You can now send the following mutation to your GraphQL API:

mutation {
  writeComment(
    userId: "__USER_ID__"
    postId: "__POST_ID__"
    text: "I like turtles 🐢"
  ) {
    id
    name
  }
}

Next steps

The idea behind the example

The Prisma client is used as a replacement for a traditional ORM in this example. It bridges the gap between your GraphQL resolvers and your database by providing a powerful CRUD API for the types that are defined in your Prisma datamodel.