프로젝트 중 외부 api를 활용하여 날짜 정보를 가져와야 하는데 날씨 테이블에 날씨 정보(Sunny, Clean 등)를 일일이 다 넣을 수 없으므로 가져온 날씨 정보가 날씨 테이블에 있는 데이터면 바로 날씨 id를 가져오고 없으면 날씨 테이블에 추가 후 id를 가져오게 만든 과정입니다.
// (1)
let currentWeather = "";
await fetch(
`http://api.weatherapi.com/v1/current.json?key=${process.env.WEATHER_API}&q=Korea&aqi=no`
)
.then((response) => response.json())
.then((data) => (currentWeather = data.current.condition.text));
// (2)
const weatherRepository = database.getRepository(Weather);
const checkWeather = await weatherRepository.findOneBy({
name: currentWeather,
});
const weather = new Weather();
if (!checkWeather) {
weather.name = currentWeather;
await database.manager.save(weather);
}
// (3)
const getWeather = await weatherRepository.findOneBy({
name: currentWeather,
});
const weatherId = getWeather?.id;
if (!weatherId) {
throw new errorConstructor(400, "잘못된 접근입니다.");
}
weather.id = weatherId;
1. 외부 api에서 날씨 데이터 가져오기
currentWeather를 현재 날씨를 저장하는 변수로 설정한다.fetch를 사용하여 외부 api를 가져온 후 currentWeather에 저장한다.2. 날씨 데이터 데이터베이스 저장
checkWeather로 currentWeather에 정보가 날씨 테이블에 있는 이름인지 확인한다.3. 데이터베이스에서 날씨 id 가져오기
getWeather에 currentWeather를 가진 데이터를 저장한다.weatherId에 getWeather에 있는 날씨 id를 할당한다.게시물 작성 과정
const createPosts = async (
title: string,
content: string,
password: string,
userId: number
) => {
const userRepository = database.getRepository(User);
const checkUserId = await userRepository.findOneBy({ id: userId });
if (!checkUserId) {
throw new errorConstructor(400, "없는 회원 아이디입니다.");
}
let currentWeather = "";
await fetch(
`http://api.weatherapi.com/v1/current.json?key=${process.env.WEATHER_API}&q=Korea&aqi=no`
)
.then((response) => response.json())
.then((data) => (currentWeather = data.current.condition.text));
const weatherRepository = database.getRepository(Weather);
const checkWeather = await weatherRepository.findOneBy({
name: currentWeather,
});
const weather = new Weather();
if (!checkWeather) {
weather.name = currentWeather;
await database.manager.save(weather);
}
const getWeather = await weatherRepository.findOneBy({
name: currentWeather,
});
const weatherId = getWeather?.id;
if (!weatherId) {
throw new errorConstructor(400, "잘못된 접근입니다.");
}
weather.id = weatherId;
const saltRound = 8;
const salt = await bcrypt.genSalt(saltRound);
const hashedPassword = await bcrypt.hash(password, salt);
const user = new User();
user.id = userId;
const posts = new Posts();
posts.title = title;
posts.content = content;
posts.password = hashedPassword;
posts.user = user;
posts.weather = weather;
await database.manager.save(posts);
};