2022.9.9.금요일 TIL: 코어 js 클래스, Express

Dorito·2022년 9월 9일
0

공부 기록

목록 보기
22/71

하루 시작

DFS 자료구조 & 알고리즘 문제 복습
코어자바스크립트 챕터 7 공부
네트워크 공부 (ip계층)
익스프레스 미들웨어 만들기

코어자바스크립트 챕터 7: 클래스

코어자바스크립트 책을 읽고 키워드 중심으로 정리한 내용입니다.

자바스크립트는 상속 개념이 없음 (프로토 타입 기반 언어)
ES6에서 클래스 문법 나타남
그러나 클래스에서 일정 부분은 프로토타입을 활용하기 때문에 ES5 체제 하에서 클래스를 흉내내기 위한 구현 방식을 학습하는 것은 중요하다.

클래스는 어떤 사물의 공통 속성을 모아 정의한 추상적 개념이고 인스턴스는 클래스의 속성을 지니는 구체적인 사례.
상위 클래스 (superclass)의 조건을 충족하면서 더욱 구체적인 조건이 추가된 것을 하위클래스 (subclass)라고 함.

  • 인스턴스에 상속되는지 여부에 따라 스태틱 멤버와 인스턴스 멤버로 나뉜다.
// 생성자
var Rectangle = function (width, height) {
  this.width = width;
  this.height = height;
};

// (프로토타입) 메서드 = 2인스턴스에서 직접 호출할 수 있는 메서드
Rectangle.prototype.getArea = function () {
  return this.width * this.height;
};

// 스태틱 메서드
Rectangle.isRectangle = function (instance) {
  return (
    instance instanceof Rectangle && instance.width > 0 && instance.height > 0
  );
};

var rectangle = new Rectangle(3, 4); // 12
console.log(rectangle.getArea()); // true



console.log(rectangle.isRectangle(rectangle)); 
/* 
* TypeError: rectangle.isRectangle is not a function
* 이유: rectangle 인스턴스에서 isRectangle 메서드에 접근하고자 함.
* 프로토타입체인을 봐도 없음 (= undefined를 실행하라 =오류) 
* -> 인스턴스에서 직접 접근할 수 없는 메서드를 스태틱 메서드라고 함.
*/


console.log(Rectangle.isRectangle(rectangle));
// 스태틱 메서드는 생성자 함수를 this로 해야만 호출할 수 있음

클래스 prototype내부에 정의된 메서드를 프로토타입 메서드라고 한다. 이 메서드들은 인스턴스가 마친 마치 자신의 것처럼 호출할 수 있음.

한편 클래스(생성자 함수)에 직접 정의한 메서드를 스태틱메서드라고 하며 이들은 인스턴스가 직접 호출할 수 없고 클래스(생성자 함수)에 의해서만 호출할 수 있다.

붕어빵 틀을 찍어낸다같은 의미에서 클래스는 추상적이지만 클래스 자체를 this로 해서 직접 접근해야만 하는 스태틱 메서드를 호출할 때 클래스는 그 자체가 하나의 개체로 취급됨.

  • 클래스 상속을 흉내내기 위한 3가지 방법 (constructor 프로퍼티가 원래 생성자 함수를 바라보도록 조정해야 함)
  1. SubClass.prototype에 SuperClass의 인스턴스를 할당한 다음 프로퍼티를 모두 삭제하는 방법
  2. 빈 함수 (Bridge)를 활용하는 방법
  3. Object.create 을 이용하는 방법

상위 클래스에 접근할 수 있는 수단인 super 구현

책 어려움... 2달뒤에 다시 읽어봐야지

Node.js Express 미들웨어 사용하기

http://expressjs.com/en/guide/using-middleware.html
An Express application can use the following types of middleware:

  • Application-level middleware
  • Router-level middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

app객체의 use메서드에 콜백 함수를 정의하는 것으로 시작함.
미들웨어 핵심은 콜백 함수의 매개변수인 요청(request), 응답(response) 객체를 받아서 활용할 수 있다는 것
next() 함수를 이용해서 그 다음 미들웨어의 실행 여부를 이전 미들웨어에서 호출(next()) 여부로 결정할 수 있다.

Application-level middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

.

Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the /user/:id path.
The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.

This example shows a middleware sub-stack that handles GET requests to the /user/:id path.

app.get('/user/:id', (req, res, next) => {
  console.log('ID:', req.params.id)
  next()
}, (req, res, next) => {
  res.send('User Info')
})

// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', (req, res, next) => {
  res.send(req.params.id)
})

To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route.

NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

This example shows a middleware sub-stack that handles GET requests to the /user/:id path.

app.get('/user/:id', (req, res, next) => {
  // if the user ID is 0, skip to the next route
  if (req.params.id === '0') next('route')
  // otherwise pass the control to the next middleware function in this stack
  else next()
}, (req, res, next) => {
  // send a regular response
  res.send('regular')
})

// handler for the /user/:id path, which sends a special response
app.get('/user/:id', (req, res, next) => {
  res.send('special')
})

Express Static file

http://expressjs.com/en/starter/static-files.html

app.use(express.static('public'))

Now, you can load the files that are in the public directory:
http://localhost:3000/images/penguin.jpeg
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

<h2>${title}</h2>${description}<img src ="/images/penguin.jpeg" style = "width: 300px; display: block; margin-top:10px">

Express 404 error handling

http://expressjs.com/en/starter/faq.html#:~:text=In%20Express%2C%20404%20responses%20are,that%20none%20of%20them%20responded.

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:

// http 404 에러 처리
app.use((require, response, next) => {
  response.status(404).send("Sorry, Can't find that~");
});

next(route) 인자 말고 다른 인자 전달하면 익스프레스는 에러가 발생한 것으로 간주함

app.get("/page/:pageId", function (request, response, next) {
  var filteredId = path.parse(request.params.pageId).base;
  fs.readFile(`data/${filteredId}`, "utf8", function (err, description) {
    if (err) {
      next(err);
    } else {
      var title = request.params.pageId;
      var sanitizedTitle = sanitizeHtml(title);
      var sanitizedDescription = sanitizeHtml(description, {
        allowedTags: ["h1"],
      });
      var list = template.list(request.list);
      var html = template.HTML(
        sanitizedTitle,
        list,
        `<h2>${sanitizedTitle}</h2>${sanitizedDescription}`,
        ` <a href="/create">create</a>
          <a href="/update/${sanitizedTitle}">update</a>
          <form action="/delete_process" method="post">
              <input type="hidden" name="id" value="${sanitizedTitle}">
              <input type="submit" value="delete">
          </form>`
      );
      response.send(html);
    }
  });
});

에러 처리가 되었긴 한데,에러 메시지가 출력하는 정보를 제어하고 싶다면 문서 참고

How do I setup an error handler?
http://expressjs.com/en/guide/error-handling.html
You define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature (err, req, res, next):

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

에러 핸들러 추가 (매개변수가 4개면 express 프레임워크는 에러 핸들러로 인식한다.)
따라서 next함수로 미들웨어를 호출할 때 인자를 전달하면 첫번째 매개변수인 err에 전달됨.

코드 아카이브


하루 마무리

  • 완료한 것 ❌ 🔺 ✅
    익스프레스 (10~14)공부 ✅
    코어자바스크립트 챕터 7 공부 ✅
    네트워크 (ip계층) 공부 ❌
    알고리즘 1 문제 풀이 ❌
  • 내일 할 것
    Express 구현 끝까지 하기
    자료구조 & 리트코드/프로그래머스 문제 1개 풀기

  • 반성
    자극에 취약해서 유튜브 보느라 생활패턴 꼬임

  • 피드백
    나 절제 못하는 사람임을 인정하고 자극을 최대한 줄이고 규칙을 만들자. (유투브 쇼츠 대신 수면 영상 틀기)

0개의 댓글