본문 바로가기
TIL

Node.js 심화 강의 1주차

by 황민도 2024. 6. 11.

내일배움캠프 스파르타 코딩클럽

 

간단하게 객체 지향 프로그래밍에 대해여 설명하고 1주차 강의 과제를 시작해 보겠다. 

 

- 객체 지향 프로그래밍 (Object-Oriented Programming, OOP) -

1. 프로그래밍 패러다임

    프로그래밍 패러다임(Programming Paradigm)은 프로그래밍 방식이나 관점을바탕으로

    효율적이고 명확한 코드를 작성하는 방법을 나타낸다.

 

    프로그래밍 세계에서 가장 대표적인 세 가지의 프로그래밍 패러다임은

    1)  구조적 프로그래밍 (Structured Programming)
         "기능 중심적 개발" 프로그래밍 이라는 기술이 시작되면서 가장 처음으로 적용된 패러다임  

    2)  객체 지향 프로그래밍 (OOP)

         "현실 세계를 프로그램으로 모델링" 하는 가장 대표적인 프로그래밍 패러다임 

    3)  함수형 프로그래밍 (Functional Programming)

         세가지 패러다임 중 가장 초기에 만들어졌지만, 최근들어 주목받기 시작한 패러다임

 

< 디렉터리 >

 

< package.json >

{
  "name": "layered-architecture-pattern",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "type": "module",
  "scripts": {
    "dev": "nodemon src/app.js",
    "format": "prettier --write *.js **/*.js"
  },
  "dependencies": {
    "@prisma/client": "^5.1.1",
    "express": "^4.18.2",
    "winston": "^3.10.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.1",
    "prettier": "^3.0.1",
    "prisma": "^5.1.1"
  }
}

 

< .gitignore >

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/

# vuepress v2.x temp and cache directory
.temp

# Serverless directories
.serverless/

# DynamoDB Local files
.dynamodb/

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# IDE - VS code
/.idea

# IDE - Jetbrains
.vscode/*
/.vscode

 

< .env >

# MySQL의 데이터베이스 URL입니다.
DATABASE_URL="mysql://root:0000@express-database.0000.ap-northeast-2.rds.amazonaws.com:3306/layered_architecture_pattern_db"

 

< prisma. schema.prisma >

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

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

model Posts {
  postId    Int      @id @default(autoincrement()) @map("postId")
  title     String   @map("title")
  content   String   @map("content") @db.Text
  nickname  String   @map("nickname")
  password  String   @map("password")
  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  @@map("Posts")
}

 

< src. app.js >

import express from 'express';
import router from './routes/index.js';
import LogMiddleware from './middlewares/log.middleware.js';
import ErrorHandlingMiddleware from './middlewares/error-handling.middleware.js';

const app = express();
const port = 4000;

app.use(LogMiddleware);
app.use(express.json());
app.use('/api', router);
app.use(ErrorHandlingMiddleware);

app.listen(port, () => {
  console.log(port, '포트로 서버가 열렸어요!');
});

 

< src.utils.prisma. index.js >

import { PrismaClient } from '@prisma/client';

export const prisma = new PrismaClient({
  // Prisma를 이용해 데이터베이스를 접근할 때, SQL을 출력해줍니다.
  log: ['query', 'info', 'warn', 'error'],

  // 에러 메시지를 평문이 아닌, 개발자가 읽기 쉬운 형태로 출력해줍니다.
  errorFormat: 'pretty',
}); // PrismaClient 인스턴스를 생성합니다.

 

< src.middlewares. error-hendling.middleware.js >

export default function (err, req, res, next) {
  console.error(err);

  res.status(500).json({ errorMessage: '서버 내부 에러가 발생했습니다.' });
}

 

< src.middlewares. log.middleware.js>

import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [new winston.transports.Console()],
});

export default function (req, res, next) {
  const start = new Date().getTime();

  res.on('finish', () => {
    const duration = new Date().getTime() - start;
    logger.info(
      `Method: ${req.method}, URL: ${req.url}, Status: ${res.statusCode}, Duration: ${duration}ms`,
    );
  });

  next();
}