-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
278 lines (249 loc) · 8.22 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
if (!process.env.HEROKU) require('dotenv/config')
var got = require('got')
var jalla = require('jalla')
var dedent = require('dedent')
var body = require('koa-body')
var mailgun = require('mailgun-js')
var compose = require('koa-compose')
var { get, post } = require('koa-route')
var asElement = require('prismic-element')
var Prismic = require('prismic-javascript')
var { URL, URLSearchParams } = require('url')
var purge = require('./lib/purge')
var imageproxy = require('./lib/cloudinary-proxy')
var { resolve, asText } = require('./components/base')
var REPOSITORY = 'https://yennengaprogress.cdn.prismic.io/api/v2'
var NOTIFICATION_RECEIVER = process.env.NODE_ENV === 'development'
var MAILGUN_DOMAIN = 'mg.yennengaprogress.se'
var MAILGUN_HOST = 'api.eu.mailgun.net'
var app = jalla('index.js', {
sw: 'sw.js',
serve: Boolean(process.env.HEROKU)
})
app.use(post('/api/join', compose([body({ multipart: true }), async function (ctx, next) {
var { given_name: givenName, family_name: familyName, email, info, linkedin, skill } = ctx.request.body
var name = `${givenName} ${familyName}`
try {
ctx.assert(givenName && familyName && email && info, 400)
var origin = process.env.NODE_ENV === 'development'
? 'http://localhost:8080'
: 'https://' + process.env.HOST
var api = await Prismic.api(REPOSITORY, { req: ctx.req })
var message = await api.getByUID('email', 'join')
var notification = await api.getByUID('email', 'notification')
var client = mailgun({
apiKey: process.env.MAILGUN_KEY,
domain: MAILGUN_DOMAIN,
host: MAILGUN_HOST
})
var url = new URL('http://yennengaprogress.info/otto/handlers/form_handler.php')
url.search = new URLSearchParams({
firstname: givenName,
lastname: familyName,
email: email,
seq: 6,
sender: 1,
a: 'sub',
ref: 'none'
})
await Promise.all([
got(url.toString()),
client.messages().send({
from: `${message.data.sender_name} <${message.data.sender_email}>`,
to: email,
subject: format(asText(message.data.subject)),
text: format(asText(message.data.body)),
html: format(asElement(message.data.body, (doc) => origin + resolve(doc)))
}),
client.messages().send({
from: `${notification.data.sender_name} <${notification.data.sender_email}>`,
to: NOTIFICATION_RECEIVER,
subject: format(asText(notification.data.subject)),
text: format(asText(notification.data.body)),
html: format(asElement(notification.data.body, (doc) => origin + resolve(doc)))
})
])
if (ctx.accepts('html')) {
ctx.redirect('back')
} else {
ctx.body = {}
ctx.type = 'application/json'
}
} catch (err) {
app.emit('error', err)
if (ctx.accepts('html')) {
ctx.redirect('back')
} else {
ctx.type = 'application/json'
ctx.status = err.status || 500
ctx.body = { error: err.message }
}
}
function format (str) {
if (Array.isArray(str)) str = str.join('')
str = str.toString()
return str
.replace(/{{\s?givenName\s?}}/ig, givenName)
.replace(/{{\s?familyName\s?}}/ig, familyName)
.replace(/{{\s?name\s?}}/ig, name)
.replace(/{{\s?info\s?}}/ig, info)
.replace(/{{\s?email\s?}}/ig, email)
.replace(/{{\s?skill\s?}}/ig, skill)
.replace(/{{\s?linkedin\s?}}/ig, linkedin)
}
}])))
/**
* Proxy image transform requests to Cloudinary
* By running all transforms through our own server we can cache the response
* on our edge servers (Cloudinary) saving on costs. Seeing as Cloudflare has
* free unlimited cache and Cloudinary does not, we will only be charged for
* the actual image transforms, of which the first 25 000 are free
*/
app.use(get('/media/:type/:transform/:uri(.+)', async function (ctx, type, transform, uri) {
if (ctx.querystring) uri += `?${ctx.querystring}`
var stream = await imageproxy(type, transform, uri)
var headers = ['etag', 'last-modified', 'content-length', 'content-type']
headers.forEach((header) => ctx.set(header, stream.headers[header]))
ctx.set('Cache-Control', `public, max-age=${60 * 60 * 24 * 365}`)
ctx.body = stream
}))
/**
* Purge Cloudflare cache whenever content is published to Prismic
*/
app.use(post('/api/prismic-hook', compose([body(), function (ctx) {
var secret = ctx.request.body && ctx.request.body.secret
ctx.assert(secret === process.env.PRISMIC_SECRET, 403, 'Secret mismatch')
return queried().then(function (urls) {
return new Promise(function (resolve, reject) {
purge(urls.concat('/sw.js'), function (err, response) {
if (err) return reject(err)
ctx.type = 'application/json'
ctx.body = {}
resolve()
})
})
})
}])))
/**
* Send donation requests as email
*/
app.use(post('/api/donate', compose([body(), function (ctx) {
var {
firstname,
lastname,
email,
ssn,
bank,
account,
clearing,
donation,
email_subject,
recipient_email,
callback_url
} = ctx.request.body;
var fullName = `${firstname} ${lastname}`
var body = `Förnamn: ${firstname}
Efternamn: ${lastname}
E-post: ${email}
Personnummer: ${ssn}
Bank: ${bank}
Kontonummer: ${account}
Clearingnummer: ${clearing}
Donation: ${donation} kr`;
const client = mailgun({
apiKey: process.env.MAILGUN_KEY,
domain: MAILGUN_DOMAIN,
host: MAILGUN_HOST
});
client.messages().send({
from: `${fullName} <${email}>`,
to: recipient_email,
subject: email_subject,
text: body
});
ctx.redirect(callback_url)
}])))
/**
* Handle Prismic previews
* Capture the preview token, setting it as a cookie and redirect to the
* document being previewed. The Prismic library will pick up the cookie and use
* it for fetching content.
*/
app.use(get('/api/prismic-preview', async function (ctx) {
var token = ctx.query.token
var api = await Prismic.api(REPOSITORY, { req: ctx.req })
var href = await api.previewSession(token, resolve, '/')
var expires = app.env === 'development'
? new Date(Date.now() + (1000 * 60 * 60 * 12))
: new Date(Date.now() + (1000 * 60 * 30))
ctx.set('Cache-Control', 'no-cache, private, max-age=0')
ctx.cookies.set(Prismic.previewCookie, token, {
expires: expires,
httpOnly: false,
path: '/'
})
ctx.redirect(href)
}))
/**
* Disallow robots anywhere but in production
*/
app.use(get('/robots.txt', function (ctx, next) {
ctx.type = 'text/plain'
ctx.body = dedent`
User-agent: *
Disallow: ${app.env === 'production' ? '' : '/'}
`
}))
/**
* Set cache headers for HTML pages
* By caching HTML on our edge servers (Cloudflare) we keep response times and
* hosting costs down. The `s-maxage` property tells Cloudflare to cache the
* response for a month whereas we set the `max-age` to cero to prevent clients
* from caching the response
*/
app.use(function (ctx, next) {
if (!ctx.accepts('html')) return next()
ctx.append('Link', '<https://use.typekit.net/ugl4huw.css>; rel=preload; crossorigin=anonymous; as=style;')
var previewCookie = ctx.cookies.get(Prismic.previewCookie)
if (previewCookie) {
ctx.set('Cache-Control', 'no-cache, private, max-age=0')
} else if (process.env.NODE_ENV !== 'development') {
ctx.set('Cache-Control', `max-age=0, s-maxage=${60 * 60 * 24 * 7}`)
}
return next()
})
/**
* Purge Cloudflare cache when starting production server
*/
app.listen(process.env.PORT || 8080, function () {
if (process.env.HEROKU && app.env === 'production') {
queried().then(function (urls) {
purge(urls.concat('/sw.js'), function (err) {
//if (err) app.emit('error', err)
if (err) console.log(err)
})
})
}
})
// get urls for all queried pages
// () -> Promise
async function queried () {
var urls = []
var api = await Prismic.api(REPOSITORY)
var [projects, news] = await Promise.all([api.query(
Prismic.Predicates.at('document.type', 'news'),
{ pageSize: 10 }
), api.query(
Prismic.Predicates.at('document.type', 'news'),
{ pageSize: 9 }
)])
for (let i = 0; i < projects.total_pages; i++) {
urls.push(`/projects?page=${i + 1}`)
}
for (let i = 0; i < news.total_pages; i++) {
urls.push(`/news?page=${i + 1}`)
}
return urls
}