📌

Express & Prisma【3Prisma 初期設定】

2022/09/20に公開

Express & Prisma【3Prisma 初期設定】

YouTube: https://youtu.be/P-deBmC_D5M

prisma quickstart: https://www.prisma.io/docs/getting-started/quickstart
prisma client: https://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/generating-prisma-client

npm install typescript @types/node --save-dev
npm install prisma --save-dev
npm install @prisma/client
npx prisma init --datasource-provider sqlite
npx prisma migrate dev --name init
npx ts-node-dev script.ts
npx prisma studio
package.json
  "dependencies": {
    "@prisma/client": "^4.3.1",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "helmet": "^6.0.0",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.12",
    "@types/express": "^4.17.14",
    "@types/morgan": "^1.9.3",
    "@types/node": "^18.7.18",
    "prisma": "^4.3.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.8.3"
  }
tsconfig.json
{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "lib": ["esnext"],
    "esModuleInterop": true
  }
}
schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

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

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  password String
  name  String?
  createdAt DateTime @default(now())
  updatedAt DateTime @default(now()) @updatedAt
  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  createdAt DateTime @default(now())
  updatedAt DateTime @default(now()) @updatedAt
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}
script.ts
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  // const user = await prisma.user.create({
  //   data: {
  //     name: 'Alice',
  //     email: 'alice@prisma.io',
  //     password: "alice"
  //   },
  // })

  const user = await prisma.user.create({
    data: {
      name: 'Bob',
      email: 'bob@prisma.io',
      password: "bob",
      posts: {
        create: {
          title: 'Hello World',
        },
      },
    },
  })

  console.log(user)
}

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

Discussion