-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
62 lines (56 loc) · 1.64 KB
/
app.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
const Prismic = require('prismic-javascript');
const PrismicDOM = require('prismic-dom');
const Cookies = require('cookies');
const request = require('request');
const PrismicConfig = require('./prismic-configuration');
const app = require('./config');
const PORT = app.get('port');
app.listen(PORT, () => {
process.stdout.write(`Point your browser to: http://localhost:${PORT}\n`);
});
/*
* Initialize prismic context and api
*/
app.use((req, res, next) => {
Prismic.getApi(PrismicConfig.apiEndpoint)
.then((api) => {
req.prismic = { api };
res.locals.RichText = PrismicDOM.RichText;
res.locals.Link = PrismicDOM.Link;
res.locals.Date = PrismicDOM.Date;
res.locals.ctx = {
endpoint: PrismicConfig.apiEndpoint,
linkResolver: PrismicConfig.linkResolver,
};
next();
}).catch((err) => {
next(err);
});
});
app.get('/', (req, res) => {
res.redirect('/page/mydoc');
});
app.get('/page/:uid', (req, res) => {
const uid = req.params.uid;
req.prismic.api.getByUID('test', uid).then((content) => {
if (content) {
res.render('index', { doc: content });
} else {
res.status(404).send('404 not found');
}
});
});
app.get('/preview', (req, res, next) => {
const token = req.query.token;
if (token) {
req.prismic.api.previewSession(token, PrismicConfig.linkResolver, '/').then((url) => {
const cookies = new Cookies(req, res);
cookies.set(Prismic.previewCookie, token, { maxAge: 30 * 60 * 1000, path: '/', httpOnly: false });
res.redirect(301, url);
}).catch((err) => {
next(err);
});
} else {
res.send(400, 'Missing token from querystring');
}
});