โš’ Backend/Node.js

[Node.js] TypeORM๋กœ CRUD ๊ตฌํ˜„ํ•ด ๋ณด๊ธฐ (feat. MySQL)

Fomagran ๐Ÿ’ป 2022. 8. 2. 03:45
728x90
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š” Foma ์ž…๋‹ˆ๋‹ค.

 

์ €๋ฒˆ ๊ธ€์—์„œ TypeORM์ด ๋ฌด์—‡์ธ์ง€์— ๋Œ€ํ•ด ๋‹ค๋ค„ ๋ณด์•˜๋Š”๋ฐ์š”.

 

์ด๋ฒˆ ๊ธ€์—์„  TypeORM์œผ๋กœ ์ƒ์„ฑ, ์กฐํšŒ, ์‚ญ์ œ, ์ˆ˜์ •์„ ๋‹ค๋ค„๋ณด๋Š” ๋ฒ•์— ๋Œ€ํ•ด์„œ ์ž‘์„ฑํ•ด ๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~


Init TypeORM

 

์šฐ์„  typeORM์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„  ์ƒ์„ฑํ•  ํ”„๋กœ์ ํŠธ ํด๋”์— typeorm ๋ชจ๋“ˆ์„ ์„ค์น˜ํ•ด ์ฃผ์…”์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

 

npm install typeorm -g

 

์•„๋ž˜์™€ ๊ฐ™์ด typeorm ํ”„๋กœ์ ํŠธ๋ฅผ ์ƒ์„ฑํ•ด ์ค๋‹ˆ๋‹ค.

 

typeorm init --name ํ”„๋กœ์ ํŠธ ์ด๋ฆ„ --database ์‚ฌ์šฉํ•  ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค

 

๊ทธ๋Ÿฌ๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ํ•ด๋‹น ๊ฒฝ๋กœ์— ํ”„๋กœ์ ํŠธ๊ฐ€ ์ƒ์„ฑ๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์„๊ฑฐ์—์š”.

 

 

ํ•ด๋‹น ํ”„๋กœ์ ํŠธ๋ฅผ VSCode๋กœ ์ผœ๋ณด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๋ช‡ ๊ฐ€์ง€ ํด๋”์™€ ํŒŒ์ผ์ด ๋ฏธ๋ฆฌ ์ƒ์„ฑ๋˜์–ด ์žˆ๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 


Set a data-source

 

data-source.ts

 

ํ•ด๋‹น ํŒŒ์ผ์€ ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค๋ฅผ ์—ฐ๊ฒฐ ์ •๋ณด๋ฅผ ์„ค์ •ํ•ด ์ฃผ๋Š” ๊ณต๊ฐ„์ž…๋‹ˆ๋‹ค.

 

import "reflect-metadata";
import { DataSource } from "typeorm";
import { Chat } from "./entity/Chat";
import { User } from "./entity/User";

export const AppDataSource = new DataSource({
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: "์œ ์ €๋„ค์ž„",
  password: "ํŒจ์Šค์›Œ๋“œ",
  database: "๋””๋น„์ด๋ฆ„",
  synchronize: true,
  logging: false,
  entities: [User, Chat],
  migrations: [],
  subscribers: [],
});

Create entities

 

๋จผ์ € ์ €๋Š” User์™€ Chat ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด ์ฃผ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

User.ts

 

@Entity() => ํ•ด๋‹น Entity์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ •ํ•จ.

 

@PrimaryGeneratedColumn() => Primary ํ‚ค์™€ ์ž๋™์œผ๋กœ ์ƒ์„ฑ๋˜๋Š” ์ปฌ๋Ÿผ์„ ์˜๋ฏธํ•จ.

 

@Column() => ์ผ๋ฐ˜์ ์ธ ์ปฌ๋Ÿผ์„ ์˜๋ฏธํ•˜๋ฉฐ ๊ด„ํ˜ธ ์‚ฌ์ด์— ์ œ์•ฝ ์กฐ๊ฑด ๋“ฑ์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Œ.

 

@OneToMany() => ์ผ๋Œ€๋‹ค ๊ด€๊ณ„๋ฅผ ๋งบ๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•จ. ex) ํ•œ ์œ ์ €์˜ ๋ชจ๋“  ์ฑ„ํŒ…์„ ๊ด€๊ณ„ ๋งบ์Œ.

 

import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";
import { Chat } from "./Chat";

@Entity({ name: "users" })
export class User {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({ type: "varchar", length: 10 })
  firstName: string;

  @Column({ nullable: false })
  lastName: string;

  @Column()
  age: number;

  @OneToMany(() => Chat, (chat) => chat.user)
  chats: Promise<Chat[]>;
}

 

Chat.ts

 

@ManyToOne() => ๋‹ค๋Œ€์ผ ๊ด€๊ณ„๋ฅผ ๋งบ๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•จ. ex) ๋ชจ๋“  ์ฑ„ํŒ…์„ ํ•œ ์œ ์ €์™€ ๊ด€๊ณ„๋ฅผ ๋งบ์Œ.

 

import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm";
import { User } from "./User";

@Entity({ name: "chats" })
export class Chat {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({ type: "varchar", length: 100 })
  content: string;

  @ManyToOne(() => User, (user) => user.chats)
  user: Promise<User>;
}

Create a controller

 

์œ ์ € ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๋งŒ๋“ค์–ด ์ƒ์„ฑ, ์กฐํšŒ, ์‚ญ์ œ, ์ˆ˜์ • ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ๊ฒ ์Šต๋‹ˆ๋‹ค.

 

import { AppDataSource } from "../data-source";
import { Chat } from "../entity/Chat";
import { User } from "../entity/User";
import { Request, Response } from "express";

export default class UserController { ...

 

Create(Insert)

 

firstName,lastName,age๋ฅผ ์š”์ฒญ์œผ๋กœ๋ถ€ํ„ฐ ๋ฐ›์•„ User ๋ ˆํฌ์ง€ํ† ๋ฆฌ์— ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

 

  addUser = async (req: Request, res: Response) => {
    let info = {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      age: req.body.age,
    };

    const userRepo = AppDataSource.getRepository(User);
    const user = userRepo.create(info);

    await userRepo
      .save(user)
      .then((data) => {
        res.json(data);
      })
      .catch((err) => console.log(err));
  };

 

Read(Get)

 

์š”์ฒญ์˜ ํŒŒ๋ผ๋ฏธํ„ฐ์˜ firstName์„ ๊ฐ€์ง„ ์œ ์ €๋ฅผ ์กฐํšŒํ•ด ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.

 

  getUser = async (req: Request, res: Response) => {
    let name = req.params.firstName;
    const userRepo = AppDataSource.getRepository(User);

    await userRepo
      .findOne({ where: { firstName: name } })
      .then((data) => {
        res.json(data);
        console.log("Get User: ", data);
      })
      .catch((err) => console.log(err));
  };

 

Read(Get)

 

๋ชจ๋“  ์œ ์ €๋ฅผ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.

 

  getAllUsers = async (req: Request, res: Response) => {
    const userRepo = AppDataSource.getRepository(User);

    await userRepo
      .findAndCount()
      .then((data) => {
        res.json(data);
        console.log("Get all User: ", data);
      })
      .catch((err) => console.log(err));
  };

 

Update

 

์š”์ฒญ์˜ ํŒŒ๋ผ๋ฏธํ„ฐ์˜ firstName์„ ๊ฐ€์ง„ ์œ ์ €์˜ ์ •๋ณด๋ฅผ ์š”์ฒญ์˜ body๋กœ ์ˆ˜์ •ํ•ด ์ค๋‹ˆ๋‹ค.

 

  updateUser = async (req: Request, res: Response) => {
    const userRepo = AppDataSource.getRepository(User);

    await userRepo
      .createQueryBuilder()
      .update(User)
      .set(req.body)
      .where({ firstName: req.params.firstName })
      .execute()
      .then((data) => {
        res.json(data);
        console.log("Update User: ", data);
      })
      .catch((err) => console.log(err));
  };

 

Delete

 

์š”์ฒญ์˜ ํŒŒ๋ผ๋ฏธํ„ฐ์˜ firstName์„ ๊ฐ€์ง„ ์œ ์ €๋ฅผ ์‚ญ์ œํ•ด ์ค๋‹ˆ๋‹ค.

 

  deleteUser = async (req: Request, res: Response) => {
    const userRepo = AppDataSource.getRepository(User);

    await userRepo
      .createQueryBuilder()
      .delete()
      .from(User)
      .where({ firstName: req.params.firstName })
      .execute()
      .then((data) => {
        res.json(data);
        console.log("Delete User: ", data);
      })
      .catch((err) => console.log(err));
  };

Set a router

 

UserController ๊ธฐ๋ฐ˜์œผ๋กœ ๋ผ์šฐํ„ฐ๋ฅผ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

import * as express from "express";
import UserController from "../controllers/UserController";

const userRouter = express.Router();

let userController = new UserController();

userRouter.post("/addUser", userController.addUser);

userRouter.get("/user/:firstName", userController.getUser);

userRouter.get("/allUsers", userController.getAllUsers);

userRouter.put("/user/:firstName", userController.updateUser);

userRouter.delete("/user/:firstName", userController.deleteUser);

export default userRouter;

Run the server

 

index.ts

 

userRouter๋ฅผ express app์— ์„ธํŒ…ํ•ด์ฃผ๊ณ  ํฌํŠธ๋ฅผ 3000๋ฒˆ์œผ๋กœ ์‹คํ–‰ ์‹œ์ผœ์ค๋‹ˆ๋‹ค.

 

import { AppDataSource } from "./data-source";
import * as express from "express";
import userRouter from "./routers/UserRouter";

const app = express();
app.use(express.json());

AppDataSource.initialize()
  .then(async () => {})
  .catch((error) => console.log(error));

app.use("/api", userRouter);
app.listen(3000, () => {
  console.log("Server running");
});

Test

 

addUser

 

//POST
http://localhost/api/addUser

//JSON
{
    "firstName":"foma",
    "lastName":"gran",
    "age":27
}

 

 

getUser

 

//GET
http://localhost/api/user/foma

 

 

getAllUsers

 

//GET
http://localhost/api/allUsers

 

 

updateUser

 

//PUT
http://localhost/api/user/foma

//JSON
{
    "firstName":"fomaaa",
    "lastName":"grannnn",
    "age":27
}

 

deleteUser

 

//DELETE
http://localhost/api/user/fomaaa

 

728x90
๋ฐ˜์‘ํ˜•