-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
189 lines (158 loc) · 5.73 KB
/
index.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const next = require('next')
const sass = require('node-sass')
const cron = require('node-cron')
const fetch = require('isomorphic-fetch')
const routes = {
images: require('./routes/images'),
amp: require('./routes/amp'),
rss: require('./routes/rss'),
rssEmail: require('./routes/rss-email'),
rssFacebook: require('./routes/rss-facebook'),
sitemap: require('./routes/sitemap'),
newsSitemap: require('./routes/news-sitemap')
}
// Load environment variables from .env file if present
require('dotenv').load()
process.env.NODE_ENV = process.env.NODE_ENV || "production"
process.env.PORT = process.env.PORT || 80
const logger = new function() {
this.log = function(err, tags) { console.log(err, tags) }
return this
}
logger.log("Instance intialized", ['startup'])
process.on('uncaughtException', function (err) {
console.log(err)
logger.log(err, ['process','uncaughtException'])
})
const app = next({
dir: '.',
dev: (process.env.NODE_ENV == 'production') ? false : true
})
const handle = app.getRequestHandler()
let trendingQuestions = []
app.prepare()
.then(() => {
const server = express()
// Debug uncaughtException errors
server.on('uncaughtException', function (req, res, route, err) {
console.log(route)
console.log(err)
logger.log({ req: req, res: res, route: route, err: err }, ['express','uncaughtException'])
if (!res.headersSent) {
return res.send(500, {ok: false})
}
res.write('\n')
res.end()
})
// Handle data submission
server.use(bodyParser.json())
server.use(bodyParser.urlencoded({ extended: true }))
// Redirect requestions to www.upsum.news to https://upsum.news/
server.use(function (req, res, next) {
if (req.hostname === "www.upsum.news") {
res.redirect(301, 'https://upsum.news' + req.originalUrl)
} else {
next()
}
})
// Improving caching behaviour across browsers
server.use(function(req, res, next) {
res.setHeader('Vary', 'Accept-Encoding')
next()
})
// Add route to serve compiled SCSS from /assets/{build id}/main.css
const sassResult = sass.renderSync({file: './css/main.scss', outputStyle: 'compressed'})
server.get('/assets/:id/main.css', (req, res) => {
res.setHeader('Content-Type', 'text/css')
res.setHeader("Cache-Control", "public, max-age=2592000")
res.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString())
res.send(sassResult.css)
})
server.get('/questions/edit/:id', (req, res) => {
if ("id" in req.params) {
return app.render(req, res, '/question/edit', req.params)
} else {
return app.render(req, res, '/', req.params)
}
})
server.get('/questions/new', (req, res) => {
return app.render(req, res, '/question/new', req.params)
})
server.get('/questions/:id', (req, res) => {
if ("id" in req.params) {
return app.render(req, res, '/question', req.params)
} else {
return app.render(req, res, '/', req.params)
}
})
server.get('/topic/:topic', (req, res) => {
if ("topic" in req.params) {
return app.render(req, res, '/topic', req.params)
} else {
return app.render(req, res, '/', req.params)
}
})
server.get('/trending-questions', (req, res) => {
return res.json(trendingQuestions)
})
// Endpoint to search and upload images to the CDN
// (middleware as the backend doesn't do this directly)
server.get('/images', routes.images.get)
server.post('/images', routes.images.post)
// Serve AMP version of questions
server.get('/amp/questions/:id', routes.amp.get)
// Serve recent questions as RSS feeeds
server.get('/rss.xml', routes.rss.get)
server.get('/rss-email.xml', routes.rssEmail.get)
server.get('/rss-facebook.xml', routes.rssFacebook.get)
// Serve sitemap (and news specific sitemap)
server.get('/sitemap.xml', routes.sitemap.get)
server.get('/news-sitemap.xml', routes.newsSitemap.get)
// Email subscription link
server.get('/email', (req, res) => {
return res.redirect(301, 'https://news.us15.list-manage1.com/subscribe?u=90920d6af43c4d73f91ca0878&id=3f929585fa')
})
// Define robots.txt to tell search engines what they should & shouldn't index
server.get('/robots.txt', function(req, res) {
res.send("Sitemap: https://upsum.news/sitemap.xml\n"+
"Sitemap: https://upsum.news/news-sitemap.xml\n"+
"User-agent: *\n"+
"Disallow: /question/new\n"+
"Disallow: /questions/new\n"+
"Disallow: /question/edit\n"+
"Disallow: /questions/edit/*\n"+
"Disallow: /signin\n")
})
// Default request handler (passes through to next.js)
server.get('*', (req, res) => {
return handle(req, res)
})
// After startup & every 5 minutes after, update cached trending questions
updateTrendingQuestions()
cron.schedule('*/2 * * * *', function(){
updateTrendingQuestions()
})
server.listen(process.env.PORT, (err) => {
if (err) throw err
require('dns').lookup(require('os').hostname(), function(err, ipAddress, fam) {
console.log('Server running at http://%s:%d in %s mode', ipAddress, process.env.PORT, process.env.NODE_ENV)
logger.log('Instance started at http://'+ipAddress+':'+process.env.PORT+' in '+process.env.NODE_ENV+' mode', ['startup'])
})
})
})
.catch(err => {
console.log('An error occurred, unable to start the server')
logger.log("Instance failed to start", ['startup'])
console.log(err)
})
const updateTrendingQuestions = async () => {
try {
const res = await fetch('https://api.upsum.news/Question?sort=-_created&limit=42')
trendingQuestions = await res.json()
} catch (e) {
console.error("Error fetching trending questions", e)
}
}