Skip to content

Commit adf52a4

Browse files
docs(): some minor tweaks
1 parent 68f4ed3 commit adf52a4

File tree

1 file changed

+54
-73
lines changed

1 file changed

+54
-73
lines changed

content/recipes/prisma.md

Lines changed: 54 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,31 @@
11
### Prisma
22

3-
[Prisma](https://www.prisma.io) is an [open-source](https://github.com/prisma/prisma) database toolkit. You can use it to query data from a database inside a Node.js or TypeScript application. Prisma and NestJS go great together since you can use Prisma in your _services_ to fulfill the data needs from your _controllers_.
3+
[Prisma](https://www.prisma.io) is an [open-source](https://github.com/prisma/prisma) database toolkit. You can use it to query data from a database inside a Node.js or TypeScript application. Prisma and NestJS go great together since you can use Prisma in your services to fulfill the data needs from your controllers.
44

5-
Prisma is used as an alternative to writing plain SQL, or using another database access tool such as SQL query builders (like [knex.js](http://knexjs.org/)) or ORMs (like [TypeORM](http://typeorm.io/) and [Sequelize](https://sequelize.org/)). Prisma currently supports PostgreSQL, MySQL and SQLite.
5+
Prisma is used as an **alternative** to writing plain SQL, or using another database access tool such as SQL query builders (like [knex.js](http://knexjs.org/)) or ORMs (like [TypeORM](http://typeorm.io/) and [Sequelize](https://sequelize.org/)). Prisma currently supports PostgreSQL, MySQL and SQLite.
66

7-
While Prisma is a _toolkit_ that contains _multiple_ tools, the focus of this guide will be on using [Prisma Client](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). Prisma Client is an auto-generated and type-safe query builder that lets you read and write data in your database.
7+
While Prisma is a toolkit\_ that contains multiple tools, the focus of this guide will be on using [Prisma Client](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). Prisma Client is an auto-generated and type-safe query builder that lets you read and write data in your database.
88

9-
> **Note** If you want to get a quick overview of how Prisma works, you can follow the [Quickstart](https://www.prisma.io/docs/getting-started/quickstart) or read the [Introduction](https://www.prisma.io/docs/understand-prisma/introduction) in the [documentation](https://www.prisma.io/docs/). There also is a great [`nestjs-prisma-starter`](https://github.com/fivethree-team/nestjs-prisma-starter) project available if you want to get started using NestJS with Prisma in production.
9+
> info **Note** If you want to get a quick overview of how Prisma works, you can follow the [Quickstart](https://www.prisma.io/docs/getting-started/quickstart) or read the [Introduction](https://www.prisma.io/docs/understand-prisma/introduction) in the [documentation](https://www.prisma.io/docs/).
1010
1111
#### Getting started
1212

13-
In this recipe, you'll learn how to get started with NestJS and Prisma from scratch. You are going to build a sample NestJS application with a REST API that can read and write data in a database.
13+
In this recipe, you'll learn how to get started with NestJS and Prisma from scratch. You are going to build a sample NestJS application with a REST API that can read and write data in a database.
1414

1515
For the purpose of this guide, you'll use a [SQLite](http://sqlite.org/) database to save the overhead of setting up a database server. Note that you can still follow this guide, even if you're using PostgreSQL or MySQL – you'll get extra instructions for using these databases at the right places.
1616

17-
In the following sections, you will:
18-
19-
1. Create your NestJS project
20-
1. Set up Prisma
21-
1. Create your SQLite database file and set the database connection
22-
1. Create two database tables
23-
1. Introspect your database to obtain your Prisma models in the Prisma schema
24-
1. Install and generate Prisma Client
25-
1. Use Prisma Client in your NestJS services
26-
1. Implement your REST API routes in the main app controller
27-
28-
##### 1. Create your NestJS project
17+
#### Create your NestJS project
2918

3019
To get started, install the NestJS CLI and create your app skeleton with the following commands:
3120

3221
```bash
33-
npm install -g @nestjs/cli
34-
nest create hello-prisma
22+
$ npm install -g @nestjs/cli
23+
$ nest new hello-prisma
3524
```
3625

37-
See the [First steps](https://docs.nestjs.com/first-steps) page to learn more about the project files created by this command. Note also that you can now run `npm start` to start your application. The REST API running at `http://localhost:3000/` currently serves a single route that's implemented in `src/app.controller.ts`. Over the course of this guide, you'll implement additional routes to store and retrieve data about _users_ and _posts_.
26+
See the [First steps](https://docs.nestjs.com/first-steps) page to learn more about the project files created by this command. Note also that you can now run `npm start` to start your application. The REST API running at `http://localhost:3000/` currently serves a single route that's implemented in `src/app.controller.ts`. Over the course of this guide, you'll implement additional routes to store and retrieve data about _users_ and _posts_.
3827

39-
##### 2. Set up Prisma
28+
#### Set up Prisma
4029

4130
Start by installing the Prisma CLI as a development dependency in your project:
4231

@@ -77,11 +66,11 @@ This command creates a new `prisma` directory with the following contents:
7766
- `schema.prisma`: Specifies your database connection and contains the database schema
7867
- `.env`: A [dotenv](https://github.com/motdotla/dotenv) file, typically used to store your database credentials in a group of environment variables
7968

80-
##### 3. Create your SQLite database file and set the database connection
69+
#### Create your SQLite database file and set the database connection
8170

8271
SQLite databases are simple files; no server is required to use a SQLite database. You can therefore create a new SQLite database by manually creating a new file on your file system.
8372

84-
Navigate into the new `prisma` directory and create a file called `dev.db` inside of it.
73+
Navigate into the new `prisma` directory and create a file called `dev.db` inside of it.
8574

8675
Next, open up `schema.prisma` and adjust the `provider` field of the `datasource` block to `sqlite`:
8776

@@ -104,7 +93,7 @@ DATABASE_URL="file:./dev.db"
10493

10594
<details><summary>Expand if you're using PostgreSQL or MySQL</summary>
10695

107-
#### PostgreSQL
96+
**PostgreSQL**
10897

10998
If you're using PostgreSQL, you have to adjust the `schema.prisma` and `.env` files as follows:
11099

@@ -121,7 +110,6 @@ generator client {
121110
}
122111
```
123112

124-
125113
**`.env`**
126114

127115
```bash
@@ -134,10 +122,9 @@ Replace the placeholders spelled in all uppercase letters with your database cre
134122
DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public"
135123
```
136124

137-
If you want to learn how to set up a PostgreSQL database, you can follow this guide on [setting up a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1).
125+
If you want to learn how to set up a PostgreSQL database, you can follow this guide on [setting up a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1).
138126

139-
140-
#### MySQL
127+
**MySQL**
141128

142129
If you're using MySQL, you have to adjust the `schema.prisma` and `.env` files as follows:
143130

@@ -164,7 +151,7 @@ Replace the placeholders spelled in all uppercase letters with your database cre
164151

165152
</details>
166153

167-
##### 4. Create two database tables
154+
#### Create two database tables
168155

169156
In this section, you'll create two new tables in your database. Run the following SQL statements in your terminal:
170157

@@ -190,7 +177,7 @@ CREATE TABLE "Post" (
190177
**Windows**
191178

192179
```bash
193-
$ sqlite3 ./prisma/dev.db
180+
$ sqlite3 ./prisma/dev.db
194181
CREATE TABLE "User" (
195182
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
196183
"name" TEXT,
@@ -205,11 +192,11 @@ CREATE TABLE "Post" (
205192
);
206193
```
207194

208-
Note that Prisma also features a _schema migration_ tool called [Prisma Migrate](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-migrate). Prisma Migrate lets you manually define your models in your Prisma schema and takes care of creating the tables in your database. Because Prisma Migrate is currently considered experimental, this guide uses an alternative workflow of using plain SQL to create your database tables and generate Prisma models via [introspection](https://www.prisma.io/docs/reference/tools-and-interfaces/introspection).
195+
Note that Prisma also features a **schema migration** tool called [Prisma Migrate](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-migrate). Prisma Migrate lets you manually define your models in your Prisma schema and takes care of creating the tables in your database. Because Prisma Migrate is currently considered experimental, this guide uses an alternative workflow of using plain SQL to create your database tables and generate Prisma models via [introspection](https://www.prisma.io/docs/reference/tools-and-interfaces/introspection).
209196

210-
##### 5. Introspect your database to obtain your Prisma models in the Prisma schema
197+
#### Introspect your database to obtain your Prisma models in the Prisma schema
211198

212-
Now that you've created your database tables, you can _introspect_ the database to generate your [Prisma models](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-schema/models). After that, you will install and generate Prisma Client, which will expose queries that are _tailored_ to these models.
199+
Now that you've created your database tables, you can **introspect** the database to generate your [Prisma models](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-schema/models). After that, you will install and generate Prisma Client, which will expose queries that are tailored to these models.
213200

214201
To introspect your database, run the following command in your terminal:
215202

@@ -248,7 +235,7 @@ model Post {
248235

249236
With your Prisma models in place, you can install and generate Prisma Client.
250237

251-
##### 6. Install and generate Prisma Client
238+
#### Install and generate Prisma Client
252239

253240
To install Prisma Client in your project, run the following command in your terminal:
254241

@@ -258,14 +245,13 @@ $ npm install @prisma/client
258245

259246
Note that during installation, Prisma automatically invokes the `prisma generate` command for you. In the future, you need to run this command after _every_ change to your Prisma models to update your generated Prisma Client.
260247

261-
> **Note** The `prisma generate` command reads your Prisma schema and updates the generated Prisma Client library inside `node_modules/@prisma/client`.
262-
248+
> info **Note** The `prisma generate` command reads your Prisma schema and updates the generated Prisma Client library inside `node_modules/@prisma/client`.
263249
264-
##### 7. Use Prisma Client in your NestJS services
250+
#### Use Prisma Client in your NestJS services
265251

266252
You're now able to send database queries with Prisma Client. If you want to learn more about building queries with Prisma Client, check out the [API documentation](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/crud).
267253

268-
When setting up your NestJS application, you'll want to abstract away the Prisma Client API for database queries within a _service_. To get started, you can create a new `PrismaService` that takes care of instantiating `PrismaClient` and connecting to your database.
254+
When setting up your NestJS application, you'll want to abstract away the Prisma Client API for database queries within a service. To get started, you can create a new `PrismaService` that takes care of instantiating `PrismaClient` and connecting to your database.
269255

270256
Inside the `src` directory, create a new file called `prisma.service.ts` and add the following code to it:
271257

@@ -276,9 +262,6 @@ import { PrismaClient } from '@prisma/client';
276262
@Injectable()
277263
export class PrismaService extends PrismaClient
278264
implements OnModuleInit, OnModuleDestroy {
279-
constructor() {
280-
super();
281-
}
282265
async onModuleInit() {
283266
await this.connect();
284267
}
@@ -316,13 +299,13 @@ export class UserService {
316299
}
317300

318301
async users(params: {
319-
skip?: number,
320-
take?: number,
321-
cursor?: UserWhereUniqueInput,
322-
where?: UserWhereInput,
323-
orderBy?: UserOrderByInput,
302+
skip?: number;
303+
take?: number;
304+
cursor?: UserWhereUniqueInput;
305+
where?: UserWhereInput;
306+
orderBy?: UserOrderByInput;
324307
}): Promise<User[]> {
325-
const { skip, take, cursor, where, orderBy } = params
308+
const { skip, take, cursor, where, orderBy } = params;
326309
return this.prisma.user.findMany({
327310
skip,
328311
take,
@@ -339,10 +322,10 @@ export class UserService {
339322
}
340323

341324
async updateUser(params: {
342-
where: UserWhereUniqueInput,
343-
data: UserUpdateInput,
325+
where: UserWhereUniqueInput;
326+
data: UserUpdateInput;
344327
}): Promise<User> {
345-
const { where, data } = params
328+
const { where, data } = params;
346329
return this.prisma.user.update({
347330
data,
348331
where,
@@ -361,7 +344,6 @@ Notice how you're using Prisma Client's generated types to ensure that the metho
361344

362345
Now do the same for the `Post` model.
363346

364-
365347
Still inside the `src` directory, create a new file called `post.service.ts` and add the following code to it:
366348

367349
```typescript
@@ -387,13 +369,13 @@ export class PostService {
387369
}
388370

389371
async posts(params: {
390-
skip?: number,
391-
take?: number,
392-
cursor?: PostWhereUniqueInput,
393-
where?: PostWhereInput,
394-
orderBy?: PostOrderByInput,
372+
skip?: number;
373+
take?: number;
374+
cursor?: PostWhereUniqueInput;
375+
where?: PostWhereInput;
376+
orderBy?: PostOrderByInput;
395377
}): Promise<Post[]> {
396-
const { skip, take, cursor, where, orderBy } = params
378+
const { skip, take, cursor, where, orderBy } = params;
397379
return this.prisma.post.findMany({
398380
skip,
399381
take,
@@ -410,10 +392,10 @@ export class PostService {
410392
}
411393

412394
async updatePost(params: {
413-
where: PostWhereUniqueInput,
414-
data: PostUpdateInput,
395+
where: PostWhereUniqueInput;
396+
data: PostUpdateInput;
415397
}): Promise<Post> {
416-
const { data, where } = params
398+
const { data, where } = params;
417399
return this.prisma.post.update({
418400
data,
419401
where,
@@ -430,7 +412,7 @@ export class PostService {
430412

431413
Your `UserService` and `PostService` currently wrap the CRUD queries that are available in Prisma Client. In a real world application, the service would also be the place to add business logic to your application. For example, you could have a method called `updatePassword` inside the `UserService` that would be responsible for updating the password of a user.
432414

433-
##### 8. Implement your REST API routes in the main app controller
415+
##### Implement your REST API routes in the main app controller
434416

435417
Finally, you'll use the services you created in the previous sections to implement the different routes of your app. For the purpose of this guide, you'll put all your routes into the already existing `AppController` class.
436418

@@ -457,19 +439,19 @@ export class AppController {
457439
private readonly postService: PostService,
458440
) {}
459441

460-
@Get('/post/:id')
442+
@Get('post/:id')
461443
async getPostById(@Param('id') id: string): Promise<PostModel> {
462444
return this.postService.post({ id: Number(id) });
463445
}
464446

465-
@Get('/feed')
447+
@Get('feed')
466448
async getPublishedPosts(): Promise<PostModel[]> {
467449
return this.postService.posts({
468450
where: { published: true },
469451
});
470452
}
471453

472-
@Get('/filterPosts/:searchString')
454+
@Get('filtered-posts/:searchString')
473455
async getFilteredPosts(
474456
@Param('searchString') searchString: string,
475457
): Promise<PostModel[]> {
@@ -487,21 +469,21 @@ export class AppController {
487469
});
488470
}
489471

490-
@Post('/post')
472+
@Post('post')
491473
async createDraft(
492474
@Body() postData: { title: string; content?: string; authorEmail: string },
493475
): Promise<PostModel> {
494-
const { title, content, authorEmail } = postData
476+
const { title, content, authorEmail } = postData;
495477
return this.postService.createPost({
496478
title,
497479
content,
498480
User: {
499-
connect: { email: authorEmail}
500-
}
481+
connect: { email: authorEmail },
482+
},
501483
});
502484
}
503485

504-
@Post('/user')
486+
@Post('user')
505487
async signupUser(
506488
@Body() userData: { name?: string; email: string },
507489
): Promise<UserModel> {
@@ -516,7 +498,7 @@ export class AppController {
516498
});
517499
}
518500

519-
@Delete('/post:id')
501+
@Delete('post/:id')
520502
async deletePost(@Param('id') id: string): Promise<PostModel> {
521503
return this.postService.deletePost({ id: Number(id) });
522504
}
@@ -525,12 +507,11 @@ export class AppController {
525507

526508
This controller implements the following routes:
527509

528-
529510
###### `GET`
530511

531512
- `/post/:id`: Fetch a single post by its `id`
532513
- `/feed`: Fetch all _published_ posts
533-
- `/filterPosts/:searchString`: Filter posts by `title` or `content`
514+
- `/filter-posts/:searchString`: Filter posts by `title` or `content`
534515

535516
###### `POST`
536517

@@ -556,4 +537,4 @@ This controller implements the following routes:
556537

557538
In this recipe, you learned how to use Prisma along with NestJS to implement a REST API. The controller that implements the routes of the API is calling a `PrismaService` which in turn uses Prisma Client to send queries to a database to fulfill the data needs of incoming requests.
558539

559-
If you want to learn more about Prisma, be sure to check out the [documentation](https://www.prisma.io/docs/).
540+
If you want to learn more about Prisma, be sure to check out the [documentation](https://www.prisma.io/docs/).

0 commit comments

Comments
 (0)