-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
68 lines (56 loc) · 1.95 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
const Koa = require('koa')
const json = require('koa-json')
const { print, chalk: { yellow } } = require('@ianwalter/print')
const Router = require('@ianwalter/router')
const pkg = require('./package.json')
// Import the JSON data copied from http://github.com/phalt/swapi.
const people = require('./data/people.json')
// Create the Koa app instance.
const app = new Koa()
// Add error-handling middleware.
app.use(async function errorHandlingMiddleware (ctx, next) {
try {
await next()
} catch (err) {
print.error(err)
ctx.status = err.statusCode || err.status || 500
}
})
// Use middleware that automatically pretty-prints JSON responses.
app.use(json())
// Add the Access-Control-Allow-Origin header that accepts all requests to the
// response.
app.use(async function disableCorsMiddleware (ctx, next) {
ctx.set('Access-Control-Allow-Origin', '*')
return next()
})
// Create the router instance.
const specifiedPort = process.env.SWAPI_PORT
const router = new Router(`http://localhost:${specifiedPort || 3000}`)
// Add a root route that provides information about the service.
router.add('/', ctx => {
ctx.body = {
name: pkg.name,
description: pkg.description,
version: pkg.version
}
})
// Add a route handler that returns 10 people per page.
router.add('/api/people', (ctx, { url }) => {
const page = url.searchParams.get('page') || 1
ctx.body = {
count: people.length,
results: people.slice((page - 1) * 10, page * 10).map(p => p.fields)
}
})
// Add a 404 Not Found handler that is executed when no routes match.
function notFoundHandler (ctx) {
ctx.status = 404
}
// Handle the request by allowing the router to route it to a handler.
app.use(ctx => router.match(ctx, notFoundHandler))
// Start listening on the specified (or randomized) port.
const server = app.listen(specifiedPort)
const { port } = server.address()
print.log('💫', yellow(`Let the force be with you: http://localhost:${port}`))
module.exports = server