Code Monkey home page Code Monkey logo

gewaechshaus_backend's Introduction

GraphQL Server Example (SDL-first)

This example shows how to implement an GraphQL server (SDL-first) with TypeScript with the following stack:

Getting started

1. Download example and install dependencies

Download this example:

curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/typescript/graphql-sdl-first

Install npm dependencies:

cd graphql-sdl-first
npm install
Alternative: Clone the entire repo

Clone this repository:

git clone [email protected]:prisma/prisma-examples.git --depth=1

Install npm dependencies:

cd prisma-examples/typescript/graphql-sdl-first
npm install

2. Create and seed the database

Run the following command to create your SQLite database file. This also creates the User and Post tables that are defined in prisma/schema.prisma:

npx prisma migrate dev --name init

Now, seed the database with the sample data in prisma/seed.ts by running the following command:

npx prisma db seed --preview-feature

3. Start the GraphQL server

Launch your GraphQL server with this command:

npm run dev

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

Using the GraphQL API

The schema that specifies the API operations of your GraphQL server is defined in ./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

Retrieve the drafts of a user

{
  draftsByUser(
    userUniqueInput: {
      email: "[email protected]"
    }
  ) {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}

Create a new user

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

Create a new draft

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

Publish/unpublish an existing post

mutation {
  togglePublishPost(id: __POST_ID__) {
    id
    published
  }
}

Note that you need to replace the __POST_ID__ placeholder with an actual id from a Post record in the database, e.g.5:

mutation {
  togglePublishPost(id: 5) {
    id
    published
  }
}

Increment the view count of a post

mutation {
  incrementPostViewCount(id: __POST_ID__) {
    id
    viewCount
  }
}

Note that you need to replace the __POST_ID__ placeholder with an actual id from a Post record in the database, e.g.5:

mutation {
  incrementPostViewCount(id: 5) {
    id
    viewCount
  }
}

Search for posts that contain a specific string in their title or content

{
  feed(
    searchString: "prisma"
  ) {
    id
    title
    content
    published
  }
}

Paginate and order the returned posts

{
  feed(
    skip: 2
    take: 2
    orderBy: { updatedAt: desc }
  ) {
    id
    updatedAt
    title
    content
    published
  }
}

Retrieve a single post

{
  postById(id: __POST_ID__ ) {
    id
    title
    content
    published
  }
}

Note that you need to replace the __POST_ID__ placeholder with an actual id from a Post record in the database, e.g.5:

{
  postById(id: 5 ) {
    id
    title
    content
    published
  }
}

Delete a post

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

Note that you need to replace the __POST_ID__ placeholder with an actual id from a Post record in the database, e.g.5:

mutation {
  deletePost(id: 5) {
    id
  }
}

Evolving the app

Evolving the application typically requires two steps:

  1. Migrate your database using Prisma Migrate
  2. Update your application code

For the following example scenario, assume you want to add "profile" feature to the app where users can create a profile and write a short bio about themselves.

1. Migrate your database using Prisma Migrate

The first step is to add a new table, e.g. called Profile, to the database. You can do this by adding a new model to your Prisma schema file file and then running a migration afterwards:

// ./prisma/schema.prisma

model User {
  id      Int      @default(autoincrement()) @id
  name    String?
  email   String   @unique
  posts   Post[]
+ profile Profile?
}

model Post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String
  content   String?
  published Boolean  @default(false)
  viewCount Int      @default(0)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

+model Profile {
+  id     Int     @default(autoincrement()) @id
+  bio    String?
+  user   User    @relation(fields: [userId], references: [id])
+  userId Int     @unique
+}

Once you've updated your data model, you can execute the changes against your database with the following command:

npx prisma migrate dev --name add-profile

This adds another migration to the prisma/migrations directory and creates the new Profile table in the database.

2. Update your application code

You can now use your PrismaClient instance to perform operations against the new `Profile table. Those operations can be used to implement queries and mutations in the GraphQL API

2.1 Add the Profile type to your GraphQL schema

First, add a new GraphQL type to your existing typeDefs:

// ./src/schema.ts

+type Profile {
+  id: ID!
+  bio: String
+  user: User
+}

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

Don't forget to include Profile and update User root types in the resolvers object

const resolvers ={
  Query: { /** as before */ },
  Mutation: { /** as before */ },
  DateTime: DateTimeResolver,
  Post: { /** as before */ },
  User: {
    posts: (parent, _args, context: Context) => {
      return context.prisma.user.findUnique({
        where: { id: parent?.id }
      }).posts()
    },
+    profile: (parent, _args, context: Context) => {
+      return context.prisma.user.findUnique({
+        where: { id: parent?.id }
+      }).profile()
+    }
  },
+  Profile: {
+    user: (parent, _args, context: Context) => {
+      return context.prisma.profile.findUnique({
+        where: { id: parent?.id }
+      }).user()
+    }
+  }
}

2.2 Add a createProfile GraphQL mutation

// ./src/schema.ts

const typeDefs = `
// other types

type Mutation {
  createDraft(authorEmail: String!, data: PostCreateInput!): Post
  deletePost(id: Int!): Post
  incrementPostViewCount(id: Int!): Post
  signupUser(data: UserCreateInput!): User!
  togglePublishPost(id: Int!): Post
+  addProfileForUser(bio: String, userUniqueInput: UserUniqueInput): Profile
}
`

const resolvers ={
  Query: { /** as before */ },
  Mutation: {
    // other mutations

+    addProfileForUser: (_parent, args: { userUniqueInput: UserUniqueInput, bio: string }, context: Context) => {
+      return context.prisma.profile.create({
+        data: {
+          bio: args.bio,
+          user: {
+            connect: {
+              id: args.userUniqueInput?.id,
+              email: args.userUniqueInput?.email
+            }
+          }
+        }
+      })
+    }
  },
  DateTime: DateTimeResolver,
  Post: { /** as before */ },
  User: { /** as before */},
  Profile: { /** as before */  }
}

Finally, you can test the new mutation like this:

mutation {
  addProfileForUser(
    userUniqueInput: {
      email: "[email protected]"
    }
    bio: "I like turtles"
  ) {
    id
    bio
    user {
      id
      name
    }
  }
}
Expand to view more sample Prisma Client queries on Profile

Here are some more sample Prisma Client queries on the new Profile model:

Create a new profile for an existing user
const profile = await prisma.profile.create({
  data: {
    bio: 'Hello World',
    user: {
      connect: { email: '[email protected]' },
    },
  },
})
Create a new user with a new profile
const user = await prisma.user.create({
  data: {
    email: '[email protected]',
    name: 'John',
    profile: {
      create: {
        bio: 'Hello World',
      },
    },
  },
})
Update the profile of an existing user
const userWithUpdatedProfile = await prisma.user.update({
  where: { email: '[email protected]' },
  data: {
    profile: {
      update: {
        bio: 'Hello Friends',
      },
    },
  },
})

Switch to another database (e.g. PostgreSQL, MySQL, SQL Server)

If you want to try this example with another database than SQLite, you can adjust the the database connection in prisma/schema.prisma by reconfiguring the datasource block.

Learn more about the different connection configurations in the docs.

Expand for an overview of example configurations with different databases

PostgreSQL

For PostgreSQL, the connection URL has the following structure:

datasource db {
  provider = "postgresql"
  url      = "postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA"
}

Here is an example connection string with a local PostgreSQL database:

datasource db {
  provider = "postgresql"
  url      = "postgresql://janedoe:mypassword@localhost:5432/notesapi?schema=public"
}

MySQL

For MySQL, the connection URL has the following structure:

datasource db {
  provider = "mysql"
  url      = "mysql://USER:PASSWORD@HOST:PORT/DATABASE"
}

Here is an example connection string with a local MySQL database:

datasource db {
  provider = "mysql"
  url      = "mysql://janedoe:mypassword@localhost:3306/notesapi"
}

Microsoft SQL Server (Preview)

Here is an example connection string with a local Microsoft SQL Server database:

datasource db {
  provider = "sqlserver"
  url      = "sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"
}

Because SQL Server is currently in Preview, you need to specify the previewFeatures on your generator block:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["microsoftSqlServer"]
}

Next steps

gewaechshaus_backend's People

Contributors

fellnerse avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.