dataController.js 4.15 KB
Newer Older
1
import db from "../db/index";
2
import dotenv from "dotenv";
KangMin An's avatar
KangMin An committed
3
4
5
import fetch from "node-fetch";
import jwt from "jsonwebtoken";
import { serverMSG, statusCode } from "../serverinfo";
6
7

dotenv.config();
8

9
// 외부 수집기로 부터 들어온 정보 처리
10
const handleOutData = async (locCode, date, lat, lng) => {
11
  // OpenWeatherAPI로 부터 지역의 날씨 정보획득을 위해 지역의 경도와 위도, API Key, 단위 기준 metric 전달
12
  const response = await fetch(
13
    `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${process.env.OPENWEATHERMAP_API_KEY}&units=metric`
14
15
16
17
18
19
20
21
  );
  const json = await response.json();

  const temp = json["main"]["temp"];
  const humi = json["main"]["humidity"];
  const press = json["main"]["pressure"];
  const wind_speed = json["wind"]["speed"];

22
23
24
25
26
27
28
29
30
31
32
33
34
  await db.Weather_out.create(
    {
      loc_code: Number(locCode),
      collected_at: date,
      temp: temp,
      humi: humi,
      press: press,
      wind_speed: wind_speed,
    },
    {
      logging: false,
    }
  );
35
36
37
};

// 내부 수집기로 부터 들어온 정보 처리
KangMin An's avatar
KangMin An committed
38
const handleInData = async (email, date, temp, humi, lights) => {
KangMin An's avatar
KangMin An committed
39
  await db.Weather_in.create(
40
    {
KangMin An's avatar
KangMin An committed
41
      host: email,
42
43
44
45
46
47
48
49
50
      collected_at: date,
      temp: temp,
      humi: humi,
      lights: lights,
    },
    {
      logging: false,
    }
  );
51
52
53
};

// 데이터 수신 처리
54
export const getDataInput = (req, res) => {
55
  try {
56
    if (req.query.type === "OUT") {
57
58
      // 외부 데이터 수집기
      const {
59
        query: { locCode, date, lat, lng },
60
      } = req;
61

KangMin An's avatar
KangMin An committed
62
63
64
65
66
67
68
69
70
71
      const trans_date = new Date(date);

      console.log(
        `Outside[${locCode}] Data(date: ${trans_date}/ lat: ${lat}/ lng: ${lng}) Input.`
      );
      handleOutData(locCode, trans_date, lat, lng);
      res.status(statusCode.ok).send({
        msg: serverMSG.server_ok,
        content: `Outside[${locCode}] data Input.`,
      });
72
73
74
    } else {
      // 내부 데이터 수집기 동작
      const {
KangMin An's avatar
KangMin An committed
75
        query: { email, date, temp, humi, lights },
76
77
      } = req;

KangMin An's avatar
KangMin An committed
78
79
80
81
82
83
      const trans_date = new Date(date);

      console.log(
        `User[${email}] Data(date: ${trans_date}/ temp: ${temp}/ humi: ${humi}/ lights: ${lights}) Input.`
      );
      handleInData(email, trans_date, temp, humi, lights);
84
85
    }

86
    res.status(statusCode.ok).send(serverMSG.server_ok);
87
88
  } catch (error) {
    console.log(error);
89
    res.status(statusCode.err).send(serverMSG.server_err);
90
  }
KangMin An's avatar
KangMin An committed
91
};
92
93

// 사용자의 데이터 가져오기 및 예측 값 전송
94
export const getUserWeatherData = (req, res) => {
95
  const {
KangMin An's avatar
KangMin An committed
96
    cookies: { acs_token },
97
98
  } = req;

99
  /* 사용자 email에 따른 사용자 날씨 데이터 가져오기 */
KangMin An's avatar
KangMin An committed
100
101
102
103
104
  const decoded = jwt.decode(acs_token);
  const result = db.Weather_in.findAll({
    where: { host: decoded.email },
    logging: false,
  });
105

KangMin An's avatar
KangMin An committed
106
  res.status(statusCode.ok).json({ msg: serverMSG.server_ok, content: result });
107
108
};

109
110
111
112
113
114
115
116
// 실외 날씨 데이터 요청 처리
export const getOutWeatherData = (req, res) => {
  // 실외 지역 번호를 통해 날씨 데이터 전송.
  res
    .status(statusCode.ok)
    .json({ msg: serverMSG.server_ok, content: "Outside Weather Data" });
};

117
// 지역 코드 요청 처리
118
export const getLocCode = async (req, res) => {
119
  /* 통합 지역 코드 및 이름 json으로 생성 및 전송 */
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
  const does = await db.Doe.findAll({ logging: false });
  const sggs = await db.Sgg.findAll({ logging: false });
  const emds = await db.Emd.findAll({ logging: false });

  let doe_sgg = [];
  let sgg_emd = [];

  does.map((info_doe) => {
    let temp = {
      name_doe: info_doe["name_doe"],
      code_doe: info_doe["code_doe"],
    };
    temp.sgg = sggs.filter(
      (info_sgg) => info_sgg["code_doe"] === info_doe["code_doe"]
    );
    doe_sgg.push(temp);
  });

  sggs.map((info_sgg) => {
    let temp = {
      code_doe: info_sgg["code_doe"],
      name_sgg: info_sgg["name_sgg"],
      code_sgg: info_sgg["code_sgg"],
    };
    temp.emd = emds.filter(
      (info_emd) => info_emd["code_sgg"] === info_sgg["code_sgg"]
    );
    sgg_emd.push(temp);
  });

  res.status(statusCode.ok).json({
    locCodes: {
      DOE: does,
      SGG: doe_sgg,
      EMD: sgg_emd,
    },
  });
157
};