/
server.js
174 lines (146 loc) · 4.92 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
'use strict';
const express = require('express');
const { json } = require('body-parser');
const request = require('request');
const multer = require('multer');
const AWS = require('aws-sdk');
//******* testing on localhost:3000 *****************************************
// const { getWeatherAPIKey, getAmazonKeys } = require('./creds/creds');
// const weatherAPIKey = process.env.WEATHER_API_KEY || getWeatherAPIKey();
// const AWSaccessKeyId = process.env.AWS_ACCESS_KEY_ID || getAmazonKeys().access_key_id;
// const AWSsecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY || getAmazonKeys().secret_access_key;
const weatherAPIKey = process.env.WEATHER_API_KEY;
//Amazon S3 config
const s3 = new AWS.S3();
// localhost:3000
// s3.config.update(
// {
// accessKeyId: AWSaccessKeyId,
// secretAccessKey: AWSsecretAccessKey,
// subregion: 'us-east-2',
// });
s3.config.update(
{
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
subregion: 'us-east-2',
});
// Multer config - memory storage keeps file data in a buffer
const upload = multer({
storage: multer.memoryStorage(),
// file size limitation in bytes
limits: { fileSize: 52428800 },
});
const app = express();
const { connect, trails, posts } = require('./db/database');
const PORT = process.env.PORT || 3000;
app.set('port', PORT);
//middlewares
app.use(express.static('client'));
app.use(json());
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// API
const Trails = trails();
const Posts = posts();
app.get('/api/wakeup', (req, res, err) => {
const msg = 'Server is waking up...'
res.send(msg);
})
app.get('/api/trails', (req, res, err) => {
Trails.find()
.then(trails => {
res.json( trails );
})
.catch(err)
})
app.patch('/api/trail', (req, res, err) => {
Trails.findOneAndUpdate({_id: req.body._id}, req.body, { upsert: true, new: true})
.then(data => res.json(data))
.catch(err)
})
app.get('/api/posts/:id', (req, res, err) => {
const trailId = req.params.id;
Posts.find( { postTrailId: trailId })
.sort( { postDate: -1 } )
.then(posts => {
res.json( posts );
})
.catch(err)
})
app.post('/api/post', (req, res, err) => {
const newPost = req.body;
Posts.create(newPost)
.then(data => res.json(data))
.catch(err)
})
app.delete('/api/closeTicket/:id', (req, res, err) => {
const id = req.params.id
Posts.findOneAndRemove({ _id: id})
.then(data => res.json(data))
.catch(err)
})
app.get('/api/weather/current/:latlon', (req, res, err) => {
const coordinates = req.params.latlon;
const weatherCallURL = `https://api.wunderground.com/api/${weatherAPIKey}/conditions/q/${coordinates}.json`;
request.get(weatherCallURL, (err, _, body) => {
res.send(body);
});
})
app.get('/api/weather/forecast/:latlon', (req, res, err) => {
const coordinates = req.params.latlon;
const weatherCallURL = `https://api.wunderground.com/api/${weatherAPIKey}/forecast/q/${coordinates}.json`;
request.get(weatherCallURL, (err, _, body) => {
// console.log("body", body);
res.send(body);
});
})
app.get('/api/weather/radar/:latlon', (req, res, err) => {
const lat = req.params.latlon.split(',')[0];
const lon = req.params.latlon.split(',')[1];
const weatherCallURL = `https://api.wunderground.com/api/${weatherAPIKey}/radar/image.gif?centerlat=${lat}¢erlon=${lon}&radius=50&width=300&height=300&newmaps=1`;
res.send(weatherCallURL);
// request.get(weatherCallURL, { encoding: null }, (err, _, body) => {
// res.set('Content-Type', 'image/gif');
// const radar ={};
// radar.image = body;
// res.send(body);
// });
})
app.post('/api/photoupload/:postType', upload.single('theseNamesMustMatch'), (req, res) => {
const postType = req.params.postType;
console.log("postType", postType);
// req.file is the 'theseNamesMustMatch' file
// console.log("req.file", req.file);
const filename = `${postType}/${req.file.originalname}`;
s3.putObject({
Bucket: 'johndhammcodes.trailtracker',
Key: filename,
Body: req.file.buffer,
ACL: 'public-read', // your permisions
}, (err, data) => {
if (err) return res.status(400).send(err);
console.log("data", data);
res.send('File uploaded to S3');
}
)
})
connect()
.then(() => {
app.listen(PORT, () => {
console.log(`Mongoose server listening on port: ${PORT}`);
});
})
.catch(console.error)