//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 ...)
//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 일 때 실행화면