TIL - Komma 프로젝트(5) - 개발환경세팅

0
post-thumbnail

컨트롤러를 구현하기 전에 먼저 세팅 작업을 하였다.

typeorm과 typescript를 사용하기 때문에 그것에 기반하여 세팅을 하였다.

$ npm init
$ npm install -g typescript
$ tsc --init
$ npm install --save-dev @types/node
$ npm install --save express body-parser
$ npm install @types/express --save-dev
$ npm install ts-node
$ npm install typeorm --save
$ npm install mysql --save
$ typeorm init --database mysql

추가적으로 .env, .gitignore, gitmessage.txt 파일을 만들어 주었다.
src 안에는 controllers와 routes폴더를 생성하였다.

tsconfig.ts
{
  "compilerOptions": {
    // 컴파일 결과물을 어떤 버전으로 할 것인지
    "target": "ES6",
    // 컴파일 된 모듈의 결과물을 어떤 모듈 시스템으로 할 것인지
    "module": "commonjs",
    "lib": ["ES5", "ES6"],
    "resolveJsonModule": true,
    // 모든 TS타입을 체크 할건지
    "moduleResolution": "node",
    "esModuleInterop": true,
    // 시작하는 루트 폴더
    "rootDir": "src",
    // 컴파일된 js파일을 어디에 둘건지
    "outDir": "dist",
    // TypeORM 사용 시 decoration 관련 옵션
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
  },
  // 어디에 있는 파일을 컴파일 할 것인지
  "include": ["src/**/*"],
  // 컴파일에서 제외되는 파일들
  "exclude": ["node_modules"]
}
package.json scripts
"scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "ts-node src/index.ts",
ormconfig
const dotenv = require('dotenv').config()
module.exports = {
   "type": "mysql",
   "host": process.env.DATABASE_HOST || "localhost",
   "port": process.env.DATABASE_PORT || 3306,
   "username": process.env.DATABASE_USERNAME || "root",
   "password": process.env.DATABASE_PASSWORD || "1234",
   "database":  process.env.DATABASE_NAME || "Komma",
   "synchronize": true,
   "logging": false,
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "src/migration",
      "subscribersDir": "src/subscriber"
   }
}
package.json
{
   "name": "Komma_Server",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "ts-node src/index.ts",
      "dev": "nodemon src/index.ts",
      "pm2:start": "pm2 start src/index.ts",
      "pm2:stop": "pm2 stop src/index.ts",
      "typeorm:create": "ts-node ./node_modules/typeorm/cli.js migration:create -n"
   },
   "repository": {
      "type": "git",
      "url": "git+https://github.com/yeonjuu417/Komma_Server.git"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "bugs": {
      "url": "https://github.com/yeonjuu417/Komma_Server/issues"
   },
   "homepage": "https://github.com/yeonjuu417/Komma_Server#readme",
   "devDependencies": {
      "@types/body-parser": "^1.19.0",
      "@types/cors": "^2.8.9",
      "@types/dotenv": "^8.2.0",
      "@types/express": "^4.17.11",
      "@types/express-session": "^1.17.3",
      "@types/helmet": "^4.0.0",
      "@types/jsonwebtoken": "^8.5.0",
      "@types/morgan": "^1.9.2",
      "@types/node": "^8.0.29",
      "@types/passport": "^1.0.5",
      "@types/passport-jwt": "^3.0.3",
      "@types/passport-local": "^1.0.33",
      "morgan": "^1.10.0",
      "ts-node": "^9.1.1",
      "typescript": "^4.1.3"
   },
   "dependencies": {
      "bcrypt": "^5.0.0",
      "bcryptjs": "^2.4.3",
      "body-parser": "^1.19.0",
      "cors": "^2.8.5",
      "crypto": "^1.0.1",
      "dotenv": "^8.2.0",
      "express": "^4.17.1",
      "express-session": "^1.17.1",
      "helmet": "^4.3.1",
      "jsonwebtoken": "^8.5.1",
      "mysql": "^2.14.1",
      "nodemon": "^2.0.7",
      "passport": "^0.4.1",
      "passport-http-bearer": "^1.0.1",
      "passport-jwt": "^4.0.0",
      "passport-local": "^1.0.0",
      "reflect-metadata": "^0.1.10",
      "typeorm": "^0.2.29"
   }
}
import "reflect-metadata";
import express from "express";
import session from "express-session";
import cors from "cors";
import logger from "morgan";
import bodyParser from "body-parser";
import { createConnection } from "typeorm";
import "dotenv/config";
const usersRouter = require('./routes/user');
createConnection()
  .then(() => console.log("typeorm connection complete"))
  .catch((error) => console.log("TypeORM connection error: ", error));
const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
  cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
    credentials: true,
  })
);
app.use(
  session({
    secret: '@codestates',
    resave: false,
    saveUninitialized: true,
    cookie: {
      maxAge: 24 * 6 * 60 * 10000,
      httpOnly: true,
      secure: true,
      sameSite: 'none',
    }
  }));
app.get('/', (req, res) => {
  res.status(200).send('Success');
});
app.use('/users', usersRouter);
const PORT = 2527;
app.listen(PORT, () => {
  console.log(`Server is Running : Port ${PORT}`);
});
module.exports = app;

설치가 모두 완료 되었으면, 필요한 컨트롤러의 파일을 만들어줬다.

그리고 라우트 설정을 하였다.

아래는 라우터 파일이다.

profile
👩🏻‍💻항상발전하자 🔥

0개의 댓글