airCondition.js 2.25 KB
var express = require("express");
var router = express.Router();
var axios = require("axios");

const openAPIKey = require("./secrets.json").openAPIKey;
const googleMapKey = require("./secrets.json").googleAPIKey;

axios.create({
  // TODO : 웹을 AWS에 올릴때, 해당 baseURL이 달라져야할 수 있음
  baseURL: "http://localhost:3001",
  responseType: "json",
});

/* GET airCondition listing. */
router.get("/", async function (req, res, next) {
  console.log("경도:", req.query.latitude);
  console.log("경도:", req.query.longitude);
  let airCondition = "";
  let response = await getPosition(req.query.latitude, req.query.longitude)
    .then((encodedStation) => getCondition(encodedStation))
    .then((result) => {
      airCondition = result;
    });

  res.send(airCondition);
});

const getPosition = (lat, lon) => {
  return axios
    .get(
      "https://maps.googleapis.com/maps/api/geocode/json?latlng=" +
        lat +
        "," +
        lon +
        "&location_type=ROOFTOP&result_type=street_address&key=" +
        googleMapKey +
        "&language=ko"
    )
    .then(function (response) {
      console.log("KEY : ", googleMapKey);
      let stationName = "";
      for (
        let i = 0;
        i < response["data"].results[0]["address_components"].length;
        i++
      ) {
        let temp =
          response["data"].results[0]["address_components"][i]["long_name"];
        if (temp[temp.length - 1] == "구") {
          stationName = temp;
          break;
        }
      }
      console.log("STATION : ", stationName);
      return (encodedStation = encodeURI(stationName));
    })
    .catch(function (error) {
      console.log(error.response);
    });
};

const getCondition = (encodedStation) => {
  return axios
    .get(
      "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty?serviceKey=" +
        openAPIKey +
        "&numOfRows=10&pageNo=1&stationName=" +
        encodedStation +
        "&dataTerm=DAILY&ver=1.3&_returnType=json"
    )
    .then(function (response) {
      // console.log("RES :: ", response);
      result = response["data"]["list"][0];
      return result;
    })
    .catch(function (error) {
      console.log(error.response);
    });
};

module.exports = router;