-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
64 lines (54 loc) · 1.42 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
// Require the framework and instantiate it
const app = require('fastify')({
logger: true
})
// Use Fastify Env plugin: https://github.com/fastify/fastify-env
const fastifyEnv = require('fastify-env') // load plugin
const options = {
confKey: 'config', // optional, default: 'config'
schema: {
type: 'object',
required: ['PORT'],
properties: {
PORT: {
type: 'string',
default: 1000
}
}
}
}
app
.register(fastifyEnv, options)
.ready((err) => {
if (err) console.error(err)
console.log(app.config)
// output: { PORT: 1000 }
})
// hooks
app.addHook('onRoute', (routeOptions) => {
console.log(`Registered route: ${routeOptions.url}`)
})
// Declare a route
app.get('/', function (req, reply) {
reply.send({ hello: 'world' })
})
// Register routes to handle blog posts
const blogRoutes = require('./routes/blogs')
blogRoutes.forEach((route, index) => {
app.route(route)
})
// Multiple parameters within same couple of slash "/"
// e.g. /example/100-500 -> prints 100 and 500
app.get('/example/:lat-:lon', (req, reply) => {
console.log(req.params.lat)
console.log(req.params.lon)
return { msg: 'success' }
})
// Run the server!
app.listen(3000, (err, address) => {
if (err) {
app.log.error(err)
process.exit(1)
}
app.log.info(`server listening on ${address}`)
})