server.js 10.4 KB
let express = require('express');
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
var request = require('request');
let session = require('express-session');
let cors = require('cors');
let app = express();
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

let logid=null;
const uri = 'mongodb+srv://sjieu17:tjrwls147714@cluster0.lc6pe.mongodb.net/weather_briefing?retryWrites=true&w=majority';
// const uri = 'mongodb+srv://tahmkench:dkrldnsl7@cluster0.vzipl.mongodb.net/?retryWrites=true&w=majority';

let db = mongoose.connect(uri, (err) => {
	if (err) {
		console.log(err.message);
	} else {
		console.log('Succesfully Connected!');
	}
});

var UserSchema = new mongoose.Schema({
	name: String,
	id: String,
  password: String,
	gender:String
});

var Users = mongoose.model('users', UserSchema);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ limit: '1gb', extended: false }));

app.post('/api/register', (req, res) => {
  
  Users.findOne({ id: req.body.id, password: req.body.password }, (err, user) => {
    if (err) return res.status(500).json({ registerSuccess: '-1'});
    else if (user){
            res.json({ registerSuccess: '0'});
        }
    else{ 
          const new_user = new Users(req.body);

          new_user.save((err) => {
              if (err) return res.status(500).json({ registerSuccess: '-1'});
              else return res.status(200).json({ registerSuccess: '1'});
          });
      }
  });

});

app.post('/api/login', (req, res) => {
 
  Users.findOne({ id: req.body.id, password: req.body.password }, (err, user) => {
		if (err) return res.status(500).json({ loginSuccess: false });
		else if (user) { 
      logData={name:user.name,gender:user.gender};
      return res.status(200).json({ loginSuccess: true, logData });
    }
		else return res.status(404).json({ loginSuccess: false });
	}); 
});

app.post('/api/logout',(req,res)=>{
  return res.status(200).json({ loginSuccess: false });
});

//변수들
// let curaddress;


//오늘의 날짜 구하기
let base,tommorow;

let today=new Date();
let CurDay=today.getFullYear().toString();
if(today.getMonth()<9){
    CurDay+="0"+(today.getMonth()+1).toString();
}
else{
    CurDay+=(today.getMonth()+1).toString();
}
if(today.getDate()<10){
    base=CurDay+"0"+(today.getDate()-1).toString();
    tommorow=CurDay+"0"+(today.getDate()+1).toString();

    CurDay+="0"+today.getDate().toString();
}
else{
    base=CurDay+(today.getDate()-1).toString();
    tommorow=CurDay+(today.getDate()+1).toString();

    CurDay+=today.getDate().toString();
}
console.log(tommorow);
//nx,ny구하기
const xlsx=require('xlsx')
const excel=xlsx.readFile('location.xlsx');
const sheet=excel.SheetNames[0];
const first=excel.Sheets[sheet];
const jsonData=xlsx.utils.sheet_to_json(first,{defval:""});
let nx,ny;

app.post('/api/address', (req, res) => {
  const addressList = [];

  for (let i = 0; i < jsonData.length; i++) {
    addressList.push({
      address1 : jsonData[i].address1,
      address2 : jsonData[i].address2,
      address3 : jsonData[i].address3,
      dotX : jsonData[i].nx,
      dotY : jsonData[i].ny,
    });
  }

  res.json(addressList);
})

let a3=[], a4=[], a5=[], a6=[], a7=[], a8=[], a9=[], a10=[], a11=[], a12=[], a13=[], a14=[], a15=[], a16=[], a17=[], a18=[], a19=[], a20=[], a21=[], a22=[], a23=[];

app.post('/api/weather',(req,res)=>{
  queryParams = '?' + encodeURIComponent('serviceKey') + '=3OcUyvx97Vx2YikiZ9IHyRQ6suapku7Xn8VlefQKQWrGIFOGaejhbevwagcubdHfSiQAqJwCV5lyIutw0%2BsppA%3D%3D';
  var url = 'http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst';

  const nx = req.body.dotX;
  const ny = req.body.dotY;
  queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1'); /* */
  queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('1000'); /* */
  queryParams += '&' + encodeURIComponent('dataType') + '=' + encodeURIComponent('JSON'); /* */
  queryParams += '&' + encodeURIComponent('base_date') + '=' + encodeURIComponent(base); /* */
  queryParams += '&' + encodeURIComponent('base_time') + '=' + encodeURIComponent('2300'); /* */
  queryParams += '&' + encodeURIComponent('nx') + '=' + encodeURIComponent(nx); /*nx*/
  queryParams += '&' + encodeURIComponent('ny') + '=' + encodeURIComponent(ny); /*ny*/
  request({
      url: url + queryParams,
      method: 'GET'
  }, function (error, response, body) {
      let ex=JSON.parse(body);
      let item=ex.response.body.items.item;
      let i=0;
      let a=[];//, a4=[], a5=[], a6=[], a7=[], a8=[], a9=[], a10=[], a11=[], a12=[], a13=[], a14=[], a15=[], a16=[], a17=[], a18=[], a19=[], a20=[], a21=[], a22=[], a23=[];
      while(item[i].fcstDate==CurDay){
          if(item[i].category=='POP' || item[i].category=='TMP'){
              a.push(item[i]);
          }
          i+=1;
      }
      let result=[];
      i=0;
      let Json;
      while(i<a.length){
          if(a[i].fcstValue<=8){
            Json={today:CurDay,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:0};
          }
          else if(a[i].fcstValue>8 && a[i].fcstValue<=12){
            Json={today:CurDay,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:1};
          }
          else if(a[i].fcstValue>12 && a[i].fcstValue<=18){
            Json={today:CurDay,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:2};
          }
          else if(a[i].fcstValue>18 && a[i].fcstValue<=23){
            Json={today:CurDay,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:3};
          }
          else{
            Json={today:CurDay,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:4};
          };
          result.push(Json);
          i+=2;
      }

      let addressData = {
        address1 : req.body.address1,
        address2 : req.body.address2,
        address3 : req.body.address3
      }
      result.push(addressData);
      res.json(result);
  });//pop:강수확률 tmp:한시간 기온
});

app.post('/api/tommorrow',(req,res)=>{
  queryParams = '?' + encodeURIComponent('serviceKey') + '=3OcUyvx97Vx2YikiZ9IHyRQ6suapku7Xn8VlefQKQWrGIFOGaejhbevwagcubdHfSiQAqJwCV5lyIutw0%2BsppA%3D%3D';
  var url = 'http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst';

  const nx = req.body.dotX;
  const ny = req.body.dotY;
  queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1'); /* */
  queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('1000'); /* */
  queryParams += '&' + encodeURIComponent('dataType') + '=' + encodeURIComponent('JSON'); /* */
  queryParams += '&' + encodeURIComponent('base_date') + '=' + encodeURIComponent(CurDay); /* */
  queryParams += '&' + encodeURIComponent('base_time') + '=' + encodeURIComponent('0200'); /* */
  queryParams += '&' + encodeURIComponent('nx') + '=' + encodeURIComponent(nx); /*nx*/
  queryParams += '&' + encodeURIComponent('ny') + '=' + encodeURIComponent(ny); /*ny*/
  request({
      url: url + queryParams,
      method: 'GET'
  }, function (error, response, body) {
      let ex=JSON.parse(body);
      let item=ex.response.body.items.item;
      let i=0;
      let a=[];//, a4=[], a5=[], a6=[], a7=[], a8=[], a9=[], a10=[], a11=[], a12=[], a13=[], a14=[], a15=[], a16=[], a17=[], a18=[], a19=[], a20=[], a21=[], a22=[], a23=[];
      while(item[i].fcstDate==tommorow||item[i].fcstDate==CurDay){
          if((item[i].category=='POP' || item[i].category=='TMP') && item[i].fcstDate==tommorow){
              a.push(item[i]);
          }
          i+=1;
      }
      let result=[];
      i=0;
      let Json;
      while(i<a.length){
          if(a[i].fcstValue<=8){
            Json={today:tommorow,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:0};
          }
          else if(a[i].fcstValue>8 && a[i].fcstValue<=12){
            Json={today:tommorow,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:1};
          }
          else if(a[i].fcstValue>12 && a[i].fcstValue<=18){
            Json={today:tommorow,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:2};
          }
          else if(a[i].fcstValue>18 && a[i].fcstValue<=23){
            Json={today:tommorow,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:3};
          }
          else{
            Json={today:tommorow,time:a[i].fcstTime[0]+a[i].fcstTime[1],temperature:a[i].fcstValue,rainPer:a[i+1].fcstValue,weather:4};
          };
          result.push(Json);
          i+=2;
      }
      res.json(result);
  });//pop:강수확률 tmp:한시간 기온
});

let mongo = require('mongoose');

// let cors = require('cors');
// let app = express();


// const uri = 'mongodb+srv://sjieu17:tjrwls147714@cluster0.lc6pe.mongodb.net/weather_briefing?retryWrites=true&w=majority';
//const uri = 'mongodb+srv://tahmkench:dkrldnsl7@cluster0.vzipl.mongodb.net/?retryWrites=true&w=majority';

let hi = mongo.connect(uri, (err) => {
	if (err) {
		console.log(err.message);
	} else {
		console.log('Succesfully Connected!');
	}
});
var clothesSchema = new mongo.Schema({
	gender: Number,
	weather: Number,
  top: Array,
	bottom:Array
});

var Clothes = mongo.model('clothes', clothesSchema);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ limit: '1gb', extended: false }));

app.post('/api/clothes', (req, res) => {
 
  Clothes.findOne({ gender: req.body.gender, weather: req.body.weather }, (err, clothes) => {
    let randt=Math.floor(Math.random()*clothes.top.length);
    let randb=Math.floor(Math.random()*clothes.bottom.length);
      if (err) return res.status(500).json({ MatchingSuccess: false });
      else if (clothes) {
         if(req.body.rain==1) return res.status(200).json({top:"../../../../../img/"+ clothes.top[randt]+".jpg",bottom:"../../../../../img/"+ clothes.bottom[randb]+".jpg",umbrella:1})
         else return res.status(200).json({top:"../../../../../img/"+ clothes.top[randt]+".jpg",bottom:"../../../../../img/"+ clothes.bottom[randb]+".jpg",umbrella:0});

        }
      else return res.status(404).json({ MatchingSuccess: false });
   }); 
});

app.listen(4000, () => console.log('Server On 4000'));