app.post("/recommend", function (req, res) {
const restaurant = req.body;
restaurant.id = uuid.v4();
const filePath = path.join(__dirname, "data", "restaurants.json");
const fileData = fs.readFileSync(filePath);
const storedRestaurants = JSON.parse(fileData);
storedRestaurants.push(restaurant);
fs.writeFileSync(filePath, JSON.stringify(storedRestaurants));
res.redirect("/confirm");
});
코드에서
const filePath = path.join(__dirname, "data", "restaurants.json");
const fileData = fs.readFileSync(filePath);
const storedRestaurants = JSON.parse(fileData);
이러한 부분이 다른 곳에서 여러 번 반복된다면 만약 어떤 것이 잘못되었을 때 일일이 모든 부분을 고쳐줘야 한다. 그러므로 이를 분리시켜서 관리할 필요가 있다.
나는 util이라는 폴더에 새로운 js파일을 만들고 거기에 함수를 하나 만들었다.
이때 js는 자바스크립트처럼 동작하므로 이 함수 안에서의 변수/상수는 함수 바깥에서 사용할 수 없다. 그러므로 필요한 상수/변수를 함수 바깥으로 빼내면 이는 restaurant-data.js파일 내부에서는 전역적으로 사용할 수 있다.
또한 가장 처음의 js코드에서
fs.writeFileSync(filePath, JSON.stringify(storedRestaurants));
restaurant-data.js파일 내부의 함수 getRestaurants의 상수를 사용하는 코드는 또한 따로 함수로 만들어주어야 한다.
const fs = require('fs');
const path = require(‘path’);
const filePath = path.join(__dirname, "data", "restaurants.json");
function getRestaurants(){
const fileData = fs.readFileSync(filePath);
const storedRestaurants = JSON.parse(fileData);
return storedRestaurants;
}
function storeRestaurant(data){
fs.writeFileSync(filePath, JSON.stringify(data));
}
코드에서 fs, path패키지를 사용하고 있으므로 이 파일에서 패키지를 다시 호출해주어야 한다. 또한 util폴더 안에 이 파일이 존재하므로
const filePath = path.join(__dirname, "data", "restaurants.json");
이러한 파일 경로 또한 알맞게 변경해 주어야 한다. 내 컴퓨터에서는 data폴더가 util폴더에서 한 단계 올라간 경로에 존재하므로
const filePath = path.join(__dirname, "..", "data", "restaurants.json");
라고 고쳤다.
이제 다른 파일에서 이 파일을 불러오려면 require(파일경로)를 사용한다.
이때 파일의 확장자는 넣으면 안 된다.
const resData = require('./util/restaurant-data');
하지만 여전히 이 파일 안의 함수들은 하나도 사용할 수 없다. 그러므로 파일의 어떤 부분을 다른 파일에서 사용할 수 있는지 restaurant-data.js파일에 명시해야 한다. 이땐 module.exports를 사용하면 된다.
module.exports = {
getRestaurants: getRestaurants,
storeRestaurant: storeRestaurant
}
module.exports에는 다른 파일로 내보내고자 하는 객체들을 명시한 객체를 할당한다. 이때 함수 자체를 사용하고 싶다면 ()를 붙여 호출하면 안되므로 주의.
이제 다른 파일에서 resData.getRestaurants 형식으로 원하던 함수를 메서드로서 사용할 수 있다.
코드를 많이 옮기지는 않았지만 처음 코드를 설계할 때 어떤 부분을 리팩토링하며 짜야하는지의 필요성을 깨달을 수 있었다. 건물을 지을 때처럼 코드의 초반 설계가 유지보수에 결정적인 역할을 하는 것 같다.