3 Layer Architecture

이연중·2021년 6월 24일
0

Node.js

목록 보기
13/14

Controller


  • 클라이언트 요청을 받고 서비스에 전달
  • 서비스에서 전달받은 결과물을 클라이언트에 응답
route.post('/', 
  validators.userSignup, // this middleware take care of validation
  async (req, res, next) => {
    // The actual responsability of the route layer.
    const userDTO = req.body;

    // Call to service layer.
    // Abstraction on how to access the data layer and the business logic.
    const { user, company } = await UserService.Signup(userDTO);

    // Return a response to client.
    return res.json({ user, company });
  });

Service


  • 비즈니스 로직 포함
  • Data Access Layer를 활용해 DB와 상호작용
  • Controller Layer에 데이터 리턴
import UserModel from '../models/user';
import CompanyModel from '../models/company';

export default class UserService() {

  async Signup(user) {
    const userRecord = await UserModel.create(user);
    const companyRecord = await CompanyModel.create(userRecord); // needs userRecord to have the database id 
    const salaryRecord = await SalaryModel.create(userRecord, companyRecord); // depends on user and company to be created
    
    ...whatever
    
    await EmailService.startSignupSequence(userRecord)

    ...do more stuff

    return { user: userRecord, company: companyRecord };
  }
}

Data Access Layer


  • 쿼리를 수행해 DB와 상호작용

주의


  • 비즈니스 로직을 Controller Layer에 넣지 말 것(Controller Layer)
  • 코드를 express.js router에서 분리할 것(Service Layer)
  • Service Layer에 req, res 객체 전달하지 말 것(Service Layer)
  • HTTP 전송 계층 관련된 것들 반환하지 말 것(Service Layer)

비즈니스 로직이란?


회원가입을 예로 들면, 사용자가 회원가입 양식 폼을 작성하고 회원가입 버튼을 누르면 회원가입이 진행된다. 이 과정에서 프로그래머는 아이디 중복 검사, 본인인증, 비밀번호 재검사를 수행한다.

먼저 프로그래머는 아이디 중복 검사를 위해 데이터베이스를 확인한다.(1)

중복된 아이디가 없으면 해당 아이디를 사용해도 된다고 사용자에게 표시해준다.(2)

(1)의 경우를 로직 or 모델 영역

(2)의 경우를 프레젠테이션 or 뷰 영역이라 한다.

즉, 비즈니스 로직이란 사용자가 요청한 데이터를 올바르게 도출하기 위해 데이터를 생성, 표시, 저장, 변경하는 코드 로직을 의미한다.

참고

https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf#architecture

profile
Always's Archives

0개의 댓글