dataController.js 5.02 KB
Newer Older
1
import db from "../db/index";
2
import envs from "../../config/config";
KangMin An's avatar
KangMin An committed
3
4
import fetch from "node-fetch";
import jwt from "jsonwebtoken";
5
import resForm from "../resForm";
6

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

16
17
18
19
    const temp = json["main"]["temp"];
    const humi = json["main"]["humidity"];
    const press = json["main"]["pressure"];
    const wind_speed = json["wind"]["speed"];
20

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    await db.Weather_Out.create(
      {
        loc_code: Number(locCode),
        collected_at: date,
        temp: temp,
        humi: humi,
        press: press,
        wind_speed: wind_speed,
      },
      {
        logging: false,
      }
    );
  } catch (err) {
    console.log("Input Weather_Out Data Error.");
    console.log(err);
  }
38
39
40
};

// 내부 수집기로 부터 들어온 정보 처리
KangMin An's avatar
KangMin An committed
41
const handleInData = async (email, date, temp, humi, lights) => {
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  try {
    await db.Weather_In.create(
      {
        host: email,
        collected_at: date,
        temp: temp,
        humi: humi,
        lights: lights,
      },
      {
        logging: false,
      }
    );
  } catch (err) {
    console.log("Input Weather_In Data Error.");
    console.log(err);
  }
59
60
61
};

// 데이터 수신 처리
62
export const getDataInput = (req, res) => {
63
  try {
64
    if (req.query.type === "OUT") {
65
66
      // 외부 데이터 수집기
      const {
67
        query: { locCode, date, lat, lng },
68
      } = req;
69

KangMin An's avatar
KangMin An committed
70
71
72
73
74
75
      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);
76
      console.log("Outside data successfully stored.");
77
78
79
    } else {
      // 내부 데이터 수집기 동작
      const {
KangMin An's avatar
KangMin An committed
80
        query: { email, date, temp, humi, lights },
81
82
      } = req;

KangMin An's avatar
KangMin An committed
83
84
85
86
87
88
      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);
89
      console.log("Inside data successfully stored.");
90
    }
91
92
93
94
    res.status(resForm.code.ok);
  } catch (err) {
    console.log(err);
    res.status(resForm.code.err);
95
  }
KangMin An's avatar
KangMin An committed
96
};
97
98

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

104
105
106
  try {
    /* 사용자 email에 따른 사용자 날씨 데이터 가져오기 */
    const decoded = jwt.decode(acs_token);
107
    const result = db.Weather_In.findAll({
108
109
110
      where: { host: decoded.email },
      logging: false,
    });
111

112
    res.json({ msg: resForm.msg.ok, contents: { weather_in: result } });
113
114
115
116
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
117
118
};

119
120
// 실외 날씨 데이터 요청 처리
export const getOutWeatherData = (req, res) => {
121
122
123
124
125
  const {
    body: { loc_code },
  } = req;
  try {
    // 실외 지역 번호를 통해 날씨 데이터 전송.
126
    const result = db.Weather_Out.findAll({
127
128
129
130
131
132
133
134
135
      where: { loc_code: loc_code },
      logging: false,
    });

    res.json({ msg: resForm.msg.ok, contents: { weather_out: result } });
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
136
137
};

138
// 지역 코드 요청 처리
139
export const getLocCode = async (req, res) => {
140
141
  try {
    /* 통합 지역 코드 및 이름 json으로 생성 및 전송 */
142
143
144
145
146
147
148
149
150
151
152
153
    const does = await db.Doe.findAll({
      order: [["name_doe", "ASC"]],
      logging: false,
    });
    const sggs = await db.Sgg.findAll({
      order: [["name_sgg", "ASC"]],
      logging: false,
    });
    const emds = await db.Emd.findAll({
      order: [["name_emd", "ASC"]],
      logging: false,
    });
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

    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.json({
      msg: resForm.msg.ok,
      contents: {
        loc_code: {
          DOE: does,
          SGG: doe_sgg,
          EMD: sgg_emd,
        },
      },
    });
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
195
};