首页 >web前端 >js教程 >使用 Prisma ORM 和 Docker Compose 来 Dockerize PERN-TypeScript 应用程序

使用 Prisma ORM 和 Docker Compose 来 Dockerize PERN-TypeScript 应用程序

Patricia Arquette
Patricia Arquette原创
2024-10-17 06:29:29749浏览

Dockerize PERN-TypeScript App Using Prisma ORM With Docker Compose

介绍

本文不做详细解释。相反,我将只提供对 PERN 堆栈应用程序进行 docker 化所需的代码片段。如果您想要更详细的解释,请查看这篇文章,我更深入地介绍了所有内容。

项目结构

pern-project/
--- frontend/
------ .dockerignore
------ frontend.dockerfile
------ ...
--- backend/
------ .dockerignore
------ backend.dockerfile
------ ...
--- docker-compose.yml

代码后端

首先创建一个node.js-express.js应用程序:

mkdir backend && cd backend
npm init -y

从 npm 安装所有必需的依赖项:

npm install express dotenv cors

同时安装 Typescript 相关的开发依赖项:

npm install --save-dev typescript ts-node @types/express @types/node @types/cors

生成 tsconfig.json 文件:

tsc --init

将 tsconfig.json 中的所有内容替换为以下代码:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDir": "./src",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts", "data-types.d.ts"]
}

在 src 文件夹中创建 src 文件夹和 index.ts 文件。所以,现在后端文件夹结构:

backend/
--- node_modules/
--- src/
------ index.ts
--- package.json
--- tsconfig.json
--- ...

将 Postgres 与 Prisma 集成

先安装 Prisma 和 Prisma 客户端:

npm i @prisma/client
npm i --save-dev prisma

生成 prisma 文件夹:

npx prisma init

在 schema.prisma 文件中写入用户模型:

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

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

model User {
  id        String   @id @default(uuid())
  name      String
  username  String
  email     String
  password  String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@map("users")
}

在 .env 文件中设置 DATABASE_URL:

DATABASE_URL=postgresql://postgres:postgres@db:5432/pern_db?schema=public

在 src 文件夹中创建文件 prismadb.ts:

import { PrismaClient } from "@prisma/client"
import "dotenv/config"

// Extend the global object with PrismaClient
declare global {
  var prisma: PrismaClient | undefined
}

// Prevent multiple instances of Prisma Client in development
const prisma = global.prisma || new PrismaClient()

if (process.env.NODE_ENV !== "production") global.prisma = prisma

export default prisma

在index.ts文件中定义/register端点。 index.ts 文件:

import express, { Request, Response } from "express"
import "dotenv/config"
import cors from "cors"
import { corsOptions } from "./constants/config"

const app = express()
const PORT = process.env.PORT || 3000

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cors({
    const corsOptions = {
    origin: process.env.CLIENT_URL || 'http://localhost:5173',
    credentials: true,
  }
}))

app.get("/", (req: Request, res: Response) => {
  res.json({
    message: "Hello, TypeScript with Express! Updated!",
  })
})

app.post("/register", async (req: Request, res: Response) => {
  const { name, username, email, password } = req.body

  await prisma.user.create({
    data: {
      name,
      username,
      email,
      password,
    },
  })

  res.json({
    message: "User created successfully",
  })
})

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
})

后端 Dockerfile

在后端目录的根目录下创建一个名为 backend.dockerfile 的文件,并写入:

FROM node:20
WORKDIR /app
COPY package*.json .
RUN npm install
COPY prisma ./prisma
RUN npx prisma generate
COPY . .
EXPOSE 3000
RUN npm install -g nodemon ts-node
CMD ["nodemon", "src/index.ts"]

要排除 node_modules,请创建一个 .dockerignore 文件:

node_modules

代码前端

创建前端:

npm create vite@latest frontend -- --template react-ts

在 React 应用程序中进行 API 调用:

// App.tsx

import { FormEvent, useEffect, useState } from "react"
....

function App() {
  const [name, setName] = useState("")
  const [username, setUsername] = useState("")
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")

  const saveUser = async (e: FormEvent) => {
    e.preventDefault()
    await fetch("http://localhost:3000/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name,
        username,
        email,
        password,
      }),
    })
      .then((res) => res.json())
      .then((data) => console.log(data))
  }

  useEffect(() => {
    fetch("http://localhost:3000")
      .then((res) => res.json())
      .then((data) => console.log(data))
  }, [])

  return (
    <>
      <form onSubmit={saveUser}>
        <input
          type="text"
          onChange={(e) => setName(e.target.value)}
          placeholder="Enter your name"
        />
        <input
          type="text"
          onChange={(e) => setUsername(e.target.value)}
          placeholder="Enter your username"
        />
        <input
          type="email"
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Enter your email"
        />
        <input
          type="password"
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Enter your password"
        />
        <button type="submit">Submit</button>
      </form>
    </>
  )
}

export default App

前端 Dockerfile

在前端目录的根目录中创建一个名为 frontend.dockerfile 的文件,并写入:

FROM node:20
WORKDIR /app
COPY package*.json .
RUN npm install
EXPOSE 5173
COPY . .
CMD [ "npm", "run", "dev" ]

Docker-Compose 文件

在后端文件夹的.env文件中添加以下内容:

// backend/.env

POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=pern_db

DATABASE_URL=postgresql://postgres:postgres@db:5432/pern_db?schema=public

docker-compose.yml 文件:

services:
  frontend:
    container_name: frontend
    build:
      context: ./frontend
      dockerfile: frontend.dockerfile
    ports:
      - "5173:5173"
    networks:
      - pern_net
    volumes:
      - ./frontend:/app
      - /app/node_modules
    depends_on:
      - server

  backend:
    container_name: backend
    build:
      context: ./backend
      dockerfile: backend.dockerfile
    env_file:
      - ./backend/.env
    ports:
      - "3000:3000"
    networks:
      - pern_net
    volumes:
      - ./backend:/app
      - /app/node_modules
    depends_on:
      - db

  db:
    container_name: db
    image: postgres:14
    restart: always
    ports:
      - "5432:5432"
    networks:
      - pern_net
    env_file:
      - ./backend/.env
    volumes:
      - pgdata:/data/db

networks:
  pern_net:
    driver: bridge

volumes:
  pgdata: {}

运行此命令:

docker compose up -d

迁移 prisma 架构:

docker backend -it backend npx prisma migrate dev --name init

以上是使用 Prisma ORM 和 Docker Compose 来 Dockerize PERN-TypeScript 应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn