> For the complete documentation index, see [llms.txt](https://jakekwak.gitbook.io/nestjs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jakekwak.gitbook.io/nestjs/recipes/untitled-5.md).

# Prisma

## Prisma

[Prisma](https://www.prisma.io/)는 데이터베이스를 GraphQL API로 바꾸고 GraphQL을 모든 데이터베이스의 범용 쿼리 언어로 사용할 수 있도록 합니다. SQL을 작성하거나 NoSQL API를 사용하는 대신 GraphQL을 사용하여 데이터베이스를 쿼리 할 수 있습니다. 이 장에서는 Prisma에 대해 자세히 다루지 않으므로 웹 사이트를 방문하여 [features](https://www.prisma.io/features/)가 무엇인지 살펴보십시오.

> warning **알림** 이 기사에서는 `Prisma`를 Nest 프레임 워크에 통합하는 방법을 학습합니다. 우리는 이미 GraphQL 개념과 `@nestjs/graphql` 모듈에 익숙하다고 가정합니다..

## Dependencies

먼저 필요한 패키지를 설치해야합니다.

```bash
$ npm install --save prisma-binding
```

## Setup Prisma

Prisma로 작업하는 동안 자신의 인스턴스를 호스팅하거나 [Prisma Cloud](https://www.prisma.io/cloud/)를 사용할 수 있습니다. 이 소개에서는 Prisma가 제공하는 데모 서버를 사용합니다.

1. Prisma CLI 설치 `npm install -g prisma`
2. 새로운 서비스 `prisma init`를 만들고 데모 서버를 선택한 다음 지시를 따르십시오
3. 서비스`prisma deploy` 배포

문제가 발생하면 [Quick Start](https://www.prisma.io/docs/quickstart/) 섹션으로 이동하여 자세한 내용을 확인하십시오. 결국 프로젝트 디렉토리에`prisma.yaml` 설정 파일이라는 두 개의 새로운 파일이 나타납니다.

```yaml
endpoint: https://us1.prisma.sh/nest-f6ec12/prisma/dev
datamodel: datamodel.graphql
```

자동으로 생성된 데이터 모델 `datamodel.graphql`.

```graphql
type User {
  id: ID! @unique
  name: String!
}
```

> warning **알림** 실제 응용 프로그램에서는 더 복잡한 데이터 모델을 만듭니다. Prisma의 데이터 모델링에 대한 자세한 내용을 보려면 [여기](https://www.prisma.io/features/data-modeling/)를 클릭하십시오.

`prisma playground`를 입력하면 Prisma GraphQL 놀이터를 열 수 있습니다.

## Create the client

GraphQL API를 통합하는 몇 가지 방법이 있습니다. 일반적인 GraphQL 개발 워크 플로우를 위한 명령 줄 도구 인 [GraphQL CLI](https://www.npmjs.com/package/graphql-cli)를 사용합니다. GraphQL CLI를 설치하려면 다음 명령을 사용하십시오.

```bash
$ npm install -g graphql-cli
```

그런 다음 Nest 애플리케이션의 루트 디렉토리에 `.graphqlconfig`를 작성하십시오.

```bash
$ touch .graphqlconfig.yml
```

다음 내용을 넣으십시오.

```yaml
projects:
  database:
    schemaPath: src/prisma/prisma-types.graphql
    extensions:
      endpoints:
        default: https://us1.prisma.sh/nest-f6ec12/prisma/dev
      codegen:
        - generator: prisma-binding
          language: typescript
          output:
            binding: src/prisma/prisma.binding.ts
```

Prisma GraphQL 스키마를 `prisma/prisma-types.graphql`로 다운로드하고 `prisma/prisma.binding.graphql`에서 Prisma 클라이언트를 작성하려면 터미널에서 다음 명령을 실행하십시오.

```bash
$ graphql get-schema --project database
$ graphql codegen --project database
```

## Integration

거의 다됐습니다. 이제 Prisma 통합을 위한 모듈을 만들어 봅시다.

```typescript
@@filename(prisma.service)
import { Injectable } from '@nestjs/common';
import { Prisma } from './prisma.binding';

@Injectable()
export class PrismaService extends Prisma {
  constructor() {
    super({
      endpoint: 'https://us1.prisma.sh/nest-f6ec12/prisma/dev',
      debug: false,
    });
  }
}
```

`PrismaService`가 준비되면 해당 모듈을 만들어야합니다.

```typescript
@@filename(prisma.module)
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';

@Module({
  providers: [PrismaService],
  exports: [PrismaService],
})
export class PrismaModule {}
```

> info **힌트** 새로운 모듈과 서비스를 즉시 생성하기 위해 [Nest CLI](https://app.gitbook.com/cli/overview)를 사용할 수 있습니다. `PrismaModule` 타잎을 만들기 위해서는 `nest g module prisma` 그리고 서비스를 위해서 `nest g service prisma`

## Usage

새 서비스를 사용하기 위해 `PrismaModule`을 가져오고 `PrismaService`를 `UsersResolver`에 주입합니다.

```typescript
@@filename(users.module)
import { Module } from '@nestjs/common';
import { UsersResolver } from './users.resolver';
import { PrismaModule } from '../prisma/prisma.module';

@Module({
  imports: [PrismaModule],
  providers: [UsersResolver],
})
export class UsersModule {}
```

`PrismaModule`을 가져 오면 `UsersModule` 컨텍스트에서 내 보낸 `PrismaService`를 사용할 수 있습니다.

```typescript
@@filename(users.resolver)
import { Query, Resolver, Args, Info } from '@nestjs/graphql';
import { PrismaService } from '../prisma/prisma.service';
import { User } from '../graphql.schema';

@Resolver()
export class UsersResolver {
  constructor(private readonly prisma: PrismaService) {}

  @Query('users')
  async getUsers(@Args() args, @Info() info): Promise<User[]> {
    return await this.prisma.query.users(args, info);
  }
}
```

## Example

약간 수정된 예제를 사용할 수 있습니다 [여기](https://github.com/nestjs/nest/tree/master/sample/22-graphql-prisma).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://jakekwak.gitbook.io/nestjs/recipes/untitled-5.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
