[네트워크] 백엔드 서버 구축

yeni·2022년 11월 22일
0

백엔드 서버 구축 실습

  • typeORM 설치
    yarn add typeorm
    yarn add pg

  • typescript설치
    yarn add --dev typescript

  • .gitignore 파일 생성 후, node_modules 제외시키기

  • tsconfig.json 파일 생성하기

//tsconfig.json
{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Recommended"
}

💡참고
[ tsconfig.json 위치 ]
https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

  • ts-node설치
    (node는 js실행기 이기 때문에 typescript를 실행할 수 있는 실행기를 설치하는것)
    yarn add ts-node

이상태에서 ts-node index.ts를 실행시키면 실행이 되지 않는다. 해결방법은 2가지가 있다.
1) ts-node도 전체 컴퓨터에 설치를 해주기
2) ts-node가 node-modules를 기반으로 실행될 수 있도록 package.json에 script를 추가해주기

yarn qqq로 실행

DB랑 백엔드 연결

// index.ts

import { DataSource } from "typeorm";
import { Board } from "./Board.postgres";

const AppDataSource = new DataSource({
  type: "postgres", // 어떤 DB에 연결할껀지?
  host: "34.64.114.80", // 컴퓨터 주소
  port: 5001,
  username: "postgres",
  password: "postgres2022",
  database: "postgres", // 이 이름은 바꿀 수 있다.
  entities: [Board],
  synchronize: true, // 작성한 코드랑 DB랑 다를경우 동기화 시켜줘!(작성한 클래스를 기준으로 동기화)
  logging: true,
});

// AppDataSource를 시작합니다!
AppDataSource.initialize()
  .then(() => {
    console.log("DB접속에 성공했습니다!");
  })
  .catch((error) => {
    console.log("DB접속에 실패했습니다!");
    console.log("원인 : ", error);
  });
// Board.postgres.ts

import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";

@Entity() //@는 함수라는 뜻 => Board 라는 table을 만들어줘!
export class Board extends BaseEntity {
  @PrimaryGeneratedColumn("increment") // 자동으로 생성되는 Primary Key를 만들어줘!(하나씩 증가하는 숫자로)
  number!: number;

  @Column({ type: "text" }) // DB type
  writer!: string; // typeScript

  @Column({ type: "text" })
  title!: string;

  @Column({ type: "text" })
  contents!: string;
}
profile
차곡차곡 쌓는 몌으니 개발노트

0개의 댓글