Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

gRPC Server Example with Prisma Postgres

This example shows how to implement a gRPC API with TypeScript and Prisma Client. It uses a Prisma Postgres database.

Getting started

1. Download example and navigate into the project directory

Download this example:

npx try-prisma@latest --template orm/grpc --install npm --name grpc

Then, navigate into the project directory:

cd grpc
Alternative: Clone the entire repo

Clone this repository:

git clone git@github.com:prisma/prisma-examples.git --depth=1

Install npm dependencies:

cd prisma-examples/orm/grpc
npm install

2. Create and seed the database

Create a new Prisma Postgres database by executing:

npx prisma init --db

If you don't have a Prisma Data Platform account yet, or if you are not logged in, the command will prompt you to log in using one of the available authentication providers. A browser window will open so you can log in or create an account. Return to the CLI after you have completed this step.

Once logged in (or if you were already logged in), the CLI will prompt you to:

  1. Select a region (e.g. us-east-1)
  2. Enter a project name

After successful creation, you will see output similar to the following:

CLI output
Let's set up your Prisma Postgres database!
? Select your region: ap-northeast-1 - Asia Pacific (Tokyo)
? Enter a project name: testing-migration
✔ Success! Your Prisma Postgres database is ready ✅

We found an existing schema.prisma file in your current project directory.

--- Database URL ---

Connect Prisma ORM to your Prisma Postgres database with this URL:

postgresql://user:password@host:port/database

--- Next steps ---

Go to https://pris.ly/ppg-init for detailed instructions.

1. Install the PostgreSQL adapter
This example uses the PostgreSQL driver adapter. If you haven't already installed it, install it in your project:
npm install @prisma/adapter-pg

2. Apply migrations
Run the following command to create and apply a migration:
npx prisma migrate dev

3. Manage your data
View and edit your data locally by running this command:
npx prisma studio

...or online in Console:
https://console.prisma.io/{workspaceId}/{projectId}/studio

4. Send queries from your app
If you already have an existing app with Prisma ORM, you can now run it and it will send queries against your newly created Prisma Postgres instance.

5. Learn more
For more info, visit the Prisma Postgres docs: https://pris.ly/ppg-docs

Locate and copy the database URL provided in the CLI output. Then, create a .env file in the project root:

touch .env

Now, paste the URL into it as a value for the DATABASE_URL environment variable. For example:

# .env
DATABASE_URL=postgresql://user:password@host:port/database

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

npx prisma migrate dev --name init

2.1. Configure Prisma Client with the adapter

This example uses the PostgreSQL driver adapter. The Prisma Client is configured in server/server.ts:

import { PrismaClient } from '../prisma/generated/client'
import { PrismaPg } from '@prisma/adapter-pg'

const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! })
const prisma = new PrismaClient({ adapter: pool })

Execute the seed file in prisma/seed.ts to populate your database with some sample data, by running:

npx prisma db seed

3. Start the gRPC server

Execute this command to start the gRPC server:

npm run dev

The server is now running on 0.0.0.0:50051.

4. Using the gRPC API

To use the gRPC API, you need a gRPC client. We provide several client scripts inside the ./client directory. Each script is named according to the operation it performs against the gRPC API (e.g. the feed.js script sends the Feed operation). Each script can be invoked by running the corresponding NPM script defined in package.json, e.g. npm run feed.

In case you prefer a GUI client, we recommend BloomRPC:

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 a "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:

// schema.prisma

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

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

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

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

npx prisma migrate dev

2. Update your application code

You can now use your PrismaClient instance to perform operations against the new Profile table. Here are some examples:

Create a new profile for an existing user

const profile = await prisma.profile.create({
  data: {
    bio: "Hello World",
    user: {
      connect: { email: "alice@prisma.io" },
    },
  },
});

Create a new user with a new profile

const user = await prisma.user.create({
  data: {
    email: "john@prisma.io",
    name: "John",
    profile: {
      create: {
        bio: "Hello World",
      },
    },
  },
});

Update the profile of an existing user

const userWithUpdatedProfile = await prisma.user.update({
  where: { email: "alice@prisma.io" },
  data: {
    profile: {
      update: {
        bio: "Hello Friends",
      },
    },
  },
});

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

If you want to try this example with another database than Postgres, 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

Your own PostgreSQL database

This example already uses a standard PostgreSQL connection with the @prisma/adapter-pg adapter. You can connect to any PostgreSQL database using a standard connection string.

SQLite

Modify the provider value in the datasource block in the prisma.schema file:

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

Create an .env file and add the SQLite database connection string in it. For example:

DATABASE_URL="file:./dev.db""

MySQL

Modify the provider value in the datasource block in the prisma.schema file:

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

Create an .env file and add a MySQL database connection string in it. For example:

## This is a placeholder url
DATABASE_URL="mysql://janedoe:mypassword@localhost:3306/notesapi"

Microsoft SQL Server

Modify the provider value in the datasource block in the prisma.schema file:

datasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
}

Create an .env file and add a Microsoft SQL Server database connection string in it. For example:

## This is a placeholder url
DATABASE_URL="sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"

MongoDB

Modify the provider value in the datasource block in the prisma.schema file:

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

Create an .env file and add a local MongoDB database connection string in it. For example:

## This is a placeholder url
DATABASE_URL="mongodb://USERNAME:PASSWORD@HOST/DATABASE?authSource=admin&retryWrites=true&w=majority"

Next steps