-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (70 loc) · 1.91 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
'use strict';
require('dotenv').config();
const express = require('express');
const exphbs = require('express-handlebars');
const url = require('url');
const fs = require('fs');
const app = express();
let stylesheet = '';
app.use('/public', express.static('public'));
// Define your favorite template engine here
app.engine('.hbs', exphbs({
defaultLayout: 'main',
extname: '.hbs',
partialsDir: 'views/components/',
helpers: {
section: function(name, options) {
if (!this._sections) this._sections = {};
this._sections[name] = options.fn(this);
return null;
}
}
}));
app.set('view engine', '.hbs');
app.set('views', 'views');
fs.readFile('./public/assets/style.css', function (err, html) {
if (err) {
throw err;
}
stylesheet = html;
});
// 1. Require the Storyblok JS client
const StoryblokClient = require('storyblok-js-client');
// 2. Initialize the client
// You can use this preview token for now, we'll change it later
const token = process.env.ACCESS_TOKEN;
let Storyblok = new StoryblokClient({
accessToken: token,
cache: {
type: 'memory'
}
});
// Define a clear cache route for the publishing hook.
app.get('/clear_cache', function(req, res) {
Storyblok.flushCache();
res.send('Cache flushed!');
});
// 3. Define a wilcard route to get the story mathing the url path
app.get('/*', function(req, res) {
var path = url.parse(req.url).pathname;
path = path == '/' ? 'home' : path;
Storyblok
.get(`cdn/stories/${path}`, {
version: req.query._storyblok ? 'draft': 'published'
})
.then((response) => {
res.render('index', {
style: stylesheet,
story: response.data.story
});
})
.catch((error) => {
res.render('index', {
style: stylesheet,
story: {}
});
});
});
app.listen((process.env.PORT || 4300), function() {
console.log('Example app listening on port 4300!');
});