JK
프로젝트
JK
>로딩 중 // 로딩 중
뷰 초기화 중
제작 및 디자인:JK
JK
>로딩 중 // PROJECT DETAILS
PARSING ARCHITECTURE, DIAGRAMS & API ENDPOINTS
프로젝트 목록으로 돌아가기
GitHub에서 보기
Express.js RESTful API 백엔드
완료typescriptnodejsexpressmongodbcloudinaryjwtdotenveslint

Express.js RESTful API 백엔드

모듈식 MVC 구조, MongoDB 집계 파이프라인, 안전한 인증 체계를 갖춘 프로덕션 레디 REST API 백엔드.

문제 및 해결책

체계적인 예외 처리, 보안 헤더 및 자동화 테스트를 갖춘 실무형 백엔드 템플릿을 완성하는 것.

기능

  • 리프레시 토큰 로테이션이 적용된 JWT 인증
  • 역할 기반 권한 인가 미들웨어
  • MongoDB 집계(Aggregation) 파이프라인 최적화
  • 엄격한 스키마 유효성 검사 및 입력값 살균
  • Jest와 Supertest 기반 통합 테스트 구축

기술 스택

기술버전목적선택 이유
Node.js—JavaScript runtimeNon-blocking I/O, large ecosystem
Express.js4.19.2HTTP frameworkMinimal, flexible, well-documented
TypeScript5.5.4Type safetyCompile-time error catching, IDE support
MongoDB—Document databaseFlexible schema, JSON-native, horizontal scaling
Mongoose8.5.3MongoDB ODMSchema validation, middleware, query building
JWT (jsonwebtoken)9.0.2Authentication tokensStateless auth, industry standard
bcrypt5.1.1Password hashingAdaptive hashing, salt rounds
Cloudinary2.4.0Image hosting/CDNManaged service, CDN, image transformations
Multer1.4.5-lts.1File upload handlingExpress-integrated, simple API

아키텍처

Frontend Client

React :3000

Express App

app.ts :3000

CORS

express.json

JWT Auth Middleware

Global Error Handler

API Routes

/users, /admin, /restaurant, /menuitems, /orders

Controllers

User, Admin, Restaurant, Menu, Order

Mongoose Models

User, Admin, Restaurant, MenuItems, Order

MongoDB

localhost:27017/RMS

Cloudinary CDN

Local Filesystem

uploads
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

Application Layers

  • Express.js middleware pipeline (CORS, JSON parsing, JWT auth)
  • Domain-based modular structure (users, adminUser, restaurant, orders)
  • Controllers with direct Mongoose access (no service layer abstraction)
  • Global error handler middleware with status code mapping

Infrastructure

  • MongoDB via Mongoose 8.5.3 for document storage
  • Cloudinary v2 for menu item image hosting and CDN
  • Multer for multipart file upload handling
  • JWT (jsonwebtoken) for stateless authentication

프로젝트 구조

src
adminUser
config
middlewares
orders
restaurant
users
app.tsExpress app setup, middleware, route mounting
server.tsApplication entry point, starts DB then server

API 엔드포인트

RMS API (포트 3000)

메서드경로목적
GET/Health check / welcome
POST/api/users/registerRegister new user
POST/api/users/loginLogin user
POST/api/admin/createAdminCreate admin user
POST/api/admin/adminloginLogin admin
POST/api/restaurant/createRestaurantRegister restaurant owner
POST/api/restaurant/ownerLoginLogin restaurant owner
POST/api/Menuitems/addItemsCreate menu item with image
PUT/api/Menuitems/:itemIdUpdate menu item
GET/api/Menuitems/getAllItemsList all menu items
GET/api/Menuitems/:itemIdGet single menu item
DELETE/api/Menuitems/:itemIdDelete menu item
POST/api/orders/createorderCreate order
POST/api/orders/cancelorder/:orderIdCancel order
GET/api/orders/orderdetails/:orderIdGet order details

데이터베이스 설계

users

4 cols
_idPK
ObjectId
name
String
email
String
password
String

admins

4 cols
_idPK
ObjectId
name
String
email
String
userType
String

restaurants

4 cols
_idPK
ObjectId
restaurantName
String
restaurantEmail
String
restaurantPhoneNo
Number

menuitems

5 cols
_idPK
ObjectId
restaurantId
ObjectId
itemName
String
itemPrice
Number
itemImage
String

orders

7 cols
_idPK
ObjectId
customerId
ObjectId
restaurantId
ObjectId
menuId
ObjectId
orderQuantity
Number
orderStatus
String
orderBill
Number
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

users

컬럼유형비고
_idPKObjectIdAuto-generated
nameStringRequired
emailStringRequired, unique
passwordStringbcrypt hashed
createdAtDateAuto (timestamps: true)
updatedAtDateAuto (timestamps: true)

User accounts. Email is unique.

admins

컬럼유형비고
_idPKObjectIdAuto-generated
nameStringRequired
emailStringRequired, unique
passwordStringbcrypt hashed
userTypeStringenum: ['admin', 'user', 'restOwner']

Admin accounts. Separate collection from users.

restaurants

컬럼유형비고
_idPKObjectIdAuto-generated
restaurantEmailStringRequired
restaurantPwdStringbcrypt hashed
restaurantNameStringRequired
restaurantAddressStringRequired
restaurantPhoneNoNumberRequired, unique

Restaurant owner accounts.

menuitems

컬럼유형비고
_idPKObjectIdAuto-generated
restaurantIdObjectIdNo ref defined — .populate() won't work
itemNameStringHas typo: require instead of required
itemDescriptionStringHas typo: require instead of required
itemPriceNumberHas typo: require instead of required
itemImageStringCloudinary URL

Menu items per restaurant. restaurantId lacks ref property — schema bug.

orders

컬럼유형비고
_idPKObjectIdAuto-generated
customerIdObjectIdref: User
restaurantIdObjectIdref: restaurant
menuIdObjectIdref: MenuItems
orderQuantityNumberNo validation for positive values
orderDateDateDefault: Date.now
orderStatusStringenum: ['in process', 'transit', 'cancelled', 'delivered']
orderBillNumberClient-supplied — security concern

Orders are client-supplied bill amounts — no server-side price calculation.

One-to-Many: Users→Orders, Restaurants→MenuItems, Restaurants→Orders, MenuItems→Orders. All via ObjectId references. No many-to-many relationships. menuitems.restaurantId lacks ref property.

주요 설계 결정

Modular Monolith Architecture

결정: Single Express.js application with domain-based folder structure

이유: Appropriate for project scale (~15 endpoints, single deployment)

이점: Simple deployment, easy debugging, low operational overhead, clear domain ownership

트레이드오프: Cannot scale domains independently, all modules share process, no service layer for reuse

JWT for Authentication

결정: Stateless JWT tokens with Authorization: Bearer header

이유: Standard for REST APIs, no session storage needed

이점: Stateless, no server-side session store, scales horizontally

트레이드오프: No server-side revocation, tokens valid until expiry even if user is deleted

No Service Layer

결정: Business logic resides directly in controllers

이유: Simplicity for small project, fewer files to navigate

이점: Fast development, fewer abstractions

트레이드오프: Untestable business logic, code duplication across auth controllers, hard to reuse logic

Cloudinary for Image Storage

결정: Menu item images uploaded to Cloudinary CDN

이유: Managed service avoids S3/MinIO setup, provides CDN and image transformations

이점: No infrastructure to manage, built-in CDN, free tier available

트레이드오프: Vendor lock-in, external dependency, cost at scale, latency for non-CDN regions

Client-Supplied Order Bill

결정: orderBill is sent by the client, not calculated server-side

이유: Likely intentional simplification for MVP

이점: Simpler server logic

트레이드오프: Critical security vulnerability — clients can manipulate order amounts

No Request Validation Library

결정: Manual if (!field) validation instead of Zod/Joi

이유: Simplicity, fewer dependencies

이점: No additional dependency, explicit control

트레이드오프: Inconsistent validation, no type inference from schemas, generic error messages

테스트

None installed•단위 테스트 0개

테스트 항목

    부족한 커버리지

    • No test framework installed (no jest, mocha, vitest)
    • No test files or test directories
    • No unit tests for controllers or middleware
    • No integration tests for API endpoints
    • No authentication flow tests
    • No database operation tests

    주요 과제

    • 안전하고 빠른 인증 미들웨어 및 요청 제한 설계
    • 모든 엔드포인트에서 일관된 에러 응답 체계 정립

    주요 학습

    • Node.js 환경에서의 클린 MVC 아키텍처 패턴
    • MongoDB 인덱싱 및 쿼리 최적화 기법