-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
executable file
·109 lines (89 loc) · 2.5 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
const Fs = require('fs')
const Hapi = require('@hapi/hapi');
const Path = require('path')
// Post Handling
const loadPosts = () => Fs.readdirSync('./posts')
.map(filename => Fs.readFileSync(`./posts/${filename}`, 'utf8'))
.map(require('./utilities/parse-post'))
const posts = loadPosts()
.filter(post => post.published_at !== undefined) // Remove unpublished posts
.filter(post => Date.now() > (new Date(post.published_at).getTime())) // Remove posts to be published in the future
.sort((a, b) => new Date(b.published_at) - new Date(a.published_at)) // Sort by date published
// Redirect Routes
const mountRedirects = (server) => {
const { redirects } = JSON.parse(Fs.readFileSync('./redirects.json', 'utf8'))
Object.entries(redirects).forEach(([from, to]) => {
server.route({
method: 'GET',
path: from,
handler: (_, h) => h.redirect(to).permanent()
})
})
}
// Post Routes
const mountPostRoutes = (server) => {
posts.forEach(post => {
server.route({
method: 'GET',
path: `/${post.slug}`,
handler: (_, h) => h.view('post', {
title: post.title,
description: post.excerpt,
image: post.og_image,
post
})
})
})
}
// Server Initialization
const bootstrap = async () => {
const server = Hapi.server({
port: process.env.PORT || 8040,
routes: {
files: { relativeTo: Path.join(__dirname, 'static') }
}
})
await server.register(require('@hapi/inert'))
await server.register(require('@hapi/vision'))
server.views({
engines: { pug: require('pug') },
relativeTo: __dirname,
path: 'views',
context: {
title: 'the frontendian',
description: 'A little blog about building web applications.',
image: '/public/img/generic_share.png'
}
})
server.route({
method: 'GET',
path: '/',
handler: (request, h) => h.view('index', { posts })
})
server.route({
method: 'GET',
path: '/feed.xml',
handler: (request, h) => h.view('rss', { posts }).type('application/atom+xml')
})
server.route({
method: 'GET',
path: '/mailing-list',
handler: (request, h) => h.view('mailing-list')
})
server.route({
method: 'GET',
path: '/{param}/',
handler: ({ path }, h) => h.redirect(path.replace(/\/$/g, '')).permanent()
})
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: { path: '.', index: false }
}
})
mountRedirects(server)
mountPostRoutes(server)
await server.start()
}
bootstrap()