-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
77 lines (68 loc) · 2.26 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
const jalla = require('jalla')
const dedent = require('dedent')
const body = require('koa-body')
const route = require('koa-route')
const geoip = require('geoip-lite')
const compose = require('koa-compose')
const Prismic = require('prismic-javascript')
const purge = require('./lib/purge')
const { resolveLink } = require('./components/base')
const PRISMIC_ENDPOINT = 'https://quantifiedplanet.cdn.prismic.io/api/v2'
const app = jalla('index.js', {sw: 'service-worker.js'})
app.use(route.get('/robots.txt', function (ctx, next) {
if (ctx.host === 'www.quantifiedplanet.org') return next()
ctx.type = 'text/plain'
ctx.body = dedent`
User-agent: *
Disallow: /
`
}))
app.use(route.post('/prismic-hook', compose([body(), async function (ctx) {
var secret = ctx.request.body && ctx.request.body.secret
ctx.assert(secret === process.env.PRISMIC_SECRET, 403, 'Secret mismatch')
return new Promise(function (resolve, reject) {
purge(function (err, response) {
if (err) return reject(err)
ctx.type = 'application/json'
ctx.body = {}
resolve()
})
})
}])))
app.use(route.get('/prismic-preview', async function (ctx) {
var token = ctx.query.token
var api = await Prismic.api(PRISMIC_ENDPOINT, {req: ctx.req})
var url = await api.previewSession(token, resolveLink, '/')
ctx.cookies.set(Prismic.previewCookie, token, {
expires: new Date(Date.now() + (1000 * 60 * 30)),
path: '/'
})
ctx.redirect(url)
}))
app.use(route.get('/geoip', function (ctx, next) {
ctx.set('Cache-Control', 'max-age=0')
ctx.type = 'application/json'
let ip = ctx.headers['cf-connecting-ip'] || ctx.ip
ctx.body = geoip.lookup(ip.replace('::1', '193.105.134.113')) || {}
}))
app.use(function (ctx, next) {
if (!ctx.accepts('html')) return next()
if (ctx.cookies.get(Prismic.previewCookie)) {
ctx.set('Cache-Control', 'max-age=0')
} else if (process.env.NODE_ENV !== 'development') {
ctx.set('Cache-Control', `s-maxage=${60 * 60 * 24 * 7}, max-age=${60}`)
}
return next()
})
if (process.env.HEROKU && process.env.NODE_ENV === 'production') {
purge(['/service-worker.js'], function (err) {
//if (err) throw err
if (err) console.log(err)
start()
})
} else {
start()
}
function start () {
app.listen(process.env.PORT || 8080)
}