GraphQL サーバー構築(その4. prismaを用いたデータベース(sqlite)の用意 )

id: 3b8292b6

## 前回
https://qiita.com/ponchuchu/items/c1370afbf7b318a973d4

## 今回やること
- [x] prisma の初期化
- [x] Prisama schema の作成
- [x] shcema の migaration 
- [x] prisma client を用いたクエリ送信
- [x] prisma studio を用いたデータベースの状態確認

### prisma の初期化
```sh: bash
$ yarn add prisma --save-dev
```

* Prisma プロジェクトをセットアップ
* 下記のコマンドでprisma/schema.prisma と .envファイルが生成される。

```sh:bash
$ npx prisma init --datasource-provider sqlite
```

### Prisama schema の作成

```text: prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

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

model Book {
  id Int @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title String
  author String
}
```


### shcema の migaration 

```sh:bash
npx prisma migrate dev --name init
```

>This command does two things:
>>1. It creates a new SQL migration file for this migration
>>2. It runs the SQL migration file against the database

https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgres

###  prisma client を用いたクエリ送信

>Import the PrismaClient constructor from the @prisma/client node module
Instantiate PrismaClient
Define an async function named main to send queries to the database
Call the main function
Close the database connections when the script terminates

https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-postgres

```sh: bash
$ yarn add  @prisma/client
```

* prisma client の作成

```ts: index.ts
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  // ... you will write your Prisma Client queries here
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
```

* prisma client を用いたクエリの作成
```ts: index.ts
async function main() {
  // ... you will write your Prisma Client queries here
  const allUsers = await prisma.user.findMany()
  console.log(allUsers)
```

* 空のデータがコンソールに表示される。
```sh:bash
$ yarn start
yarn run v1.22.19
$ npm run compile && node ./dist/index.js

> graphql-server-example@1.0.0 compile
> tsc

[]
```

* databaseへの書き込み
```ts: index.ts
async function main() {
  await prisma.book.create({
    data:{
      title: "intial-title",
      author: "initial-author"
    }
  });
  
  const allBooks = await prisma.book.findMany()
  console.log(allBooks)
```

```sh:bash
$ yarn start
yarn run v1.22.19
$ npm run compile && node ./dist/index.js

> graphql-server-example@1.0.0 compile
> tsc

[
  {
    id: 1,
    createdAt: 2022-12-31T06:43:08.108Z,
    updatedAt: 2022-12-31T06:43:08.108Z,
    title: 'intial-title',
    author: 'initial-author'
  }
```

### prisma studio を用いたデータベースの状態確認![2022-12-31_15h48_02.png]

* 下記コマンドで起動
```sh:bash
$ npx prisma studio
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Prisma Studio is up on http://localhost:5555
```
GUI上でBookテーブルの状態が確認できる。
![2022-12-31_15h48_02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2193053/8882813e-e4fd-80b4-5388-7dfa3f44f828.png)

## 次回
- [ ] prismaとgraphqlサーバーの接続
- [ ] grahql codegenの利用