paginated API test (2)

unow30·2020년 12월 27일
0

experss

목록 보기
8/8

이전편

페이징 기능을 미들웨어로 추상화하기

  • 이제 "/users" url 호출로 users 객체를 불러 패이징할 수 있다. 그러나 다른 url 호출로 패이징을 하려면 이전에 작성했던 패이징 기능을 그대로 추가해야 한다.
  • 중복코드가 생기는 것은 보기도 않좋고 단순 반복작업이 되기 때문에 패이징 기능을 미들웨어로 분리해서 실행하도록 한다.
//index.js

//const users = {...}

const posts = [
    { id: 1, name: "post1" },
    { id: 2, name: "post2" },
    { id: 3, name: "post3" },
    { id: 4, name: "post4" },
    { id: 5, name: "post5" },
    { id: 6, name: "post6" },
    { id: 7, name: "post7" },
    { id: 8, name: "post8" },
    { id: 9, name: "post9" },
    { id: 10, name: "post10" },
    { id: 11, name: "post11" },
    { id: 12, name: "post12" },
    { id: 13, name: "post13" },
]

app.get("/posts", (req, res) => {
    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)

    const startIndex = (page - 1) * limit
    const endIndex = page * limit

    const results = {}



    if (startIndex > 0) {
        results.previous = {
            previous: page - 1,
            limit: limit
        }
    }
    if (endIndex < users.length)
        results.next = {
            next: page + 1,
            limit: limit
        }
    results.result = users.slice(startIndex, endIndex);

    // res.json(users)
    res.json(results)
})

//app.get("users ...)
  • "/posts"라는 url 호출을 받아 posts 객체를 패이징하는 코드이다. 원래는 라우팅 기능으로 분리하는 것이 좋지만 연습과정이라 index.js 파일에 전부 추가했다.
  • users에서 봤던 패이징 기능이 그대로 들어가있다. 이러면 패이징을 해야하는 rest 호출에서 매번 이 여러줄의 코드를 복붙해야 한다.
  • paginatedResult 메소드를 만들어 url 호출의 인자로 추가한다.
//index.js
//이전 내용 생략

//편의상 index.js에 함수를 입력했다. 다른 폴더에 저장하여 require 하는 것이 좋다. 위치상 app.get()보다 위에 있어야 이 함수를 읽고 실행할 수 있다.
const paginatedResults = (obj) => {
  	
  return (req, res, next) =>{
    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)

    const startIndex = (page - 1) * limit
    const endIndex = page * limit

    const results = {}



    if (startIndex > 0) {
        results.previous = {
            previous: page - 1,
            limit: limit
        }
    }
    if (endIndex < obj.length)
        results.next = {
            next: page + 1,
            limit: limit
        }
    results.result = obj.slice(startIndex, endIndex);   
    
    res.paginatedResults = results
    next();
    }
}    

app.get("/posts", paginatedResults(posts), (req, res) =>{
	res.json(res.paginatedResults)
}
        
app.get("/users", paginatedResults(users), (req, res) =>{
	res.json(res.paginatedResults)
}
        
  • app.get()의 인자 설명
    app.get() 호출의 인자 중에서 콜백 함수를 살펴보면 미들웨어 기능을 추가할 수 있다고 한다.( ,를 이용해 여러 미들웨어를 입력할 수도 있다.)

  • 미들웨어 함수에는 반드시 (req, res, next)를 포함한다. next가 있어야 미들웨어 함수가 끝나고 다음 미들웨어 함수를 실행시킬 수 있다.

/posts 일 때 실행화면/users 일 때 실행화면

0개의 댓글