This repository has been archived by the owner on Dec 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
executable file
·165 lines (147 loc) · 4.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#! /usr/bin/env node
const program = require('commander')
program
.option('-p, --port [number]', 'port to launch API on')
.option('-l, --logging [value]', 'Log level')
.parse(process.argv)
const jsonServer = require('json-server')
const url = require('url')
const lodash = require('lodash')
const glob = require('glob')
let server = jsonServer.create()
let router = jsonServer.router()
let middlewares = jsonServer.defaults()
init()
function init () {
server.use(jsonServer.bodyParser)
if (program.logging) {
console.log('Logging has been enabled')
}
server.use(function (req, res, next) {
if (program.logging && program.logging === 'debug') {
console.log(req.body)
}
next()
})
loadDataFiles().then(function (resp) { // We load all endpoints
return loadLocalOverrideFiles(resp)
})
.then(function (endpoints) { // We apply local endpoint overrides
let uniqueURLS = 0
lodash.forIn(endpoints, function (data, endpointName) {
uniqueURLS += Object.keys(data).length
buildRESTRoute(data, endpointName) // This builds the rest route
})
console.log(`Endpoints loaded ${Object.keys(endpoints).length}`)
console.log(`Unique URLS loaded ${uniqueURLS}`)
startServer()
})
}
function startServer () {
server.use(jsonServer.rewriter({
'/api/:resource': '/:resource'
}))
server.use(middlewares)
server.use(function (req, res) {
res.sendStatus(501)
})
server.use(router)
let port = 3000
if (program.port) {
port = program.port
} else if (process.env.MOCK_API_HOST) {
let urlParts = url.parse(process.env.MOCK_API_HOST, false)
port = urlParts.host
}
server.listen(port, function () {
console.log(`Mock API Server is running on port ${port}`)
})
}
function loadDataFiles () {
let allEndpoints = {}
return new Promise(
function (resolve, reject) {
glob('./data/**/*.json', function (er, files) {
files.forEach(function (file) {
allEndpoints = processFile(file, allEndpoints)
})
resolve(allEndpoints)
})
})
}
function loadLocalOverrideFiles (allEndpoints) {
return new Promise(
function (resolve, reject) {
glob('./local/**/*.json', function (er, files) {
files.forEach(function (file) {
allEndpoints = processFile(file, allEndpoints)
})
resolve(allEndpoints)
})
})
}
function processFile (file, allEndpoints) {
const dataFile = require(file)
let urlParts = url.parse(dataFile.url)
let endpoint = urlParts.pathname
// if it is a sub-path deal with stripping out endpoint and create a
if (endpoint.includes('/')) {
let urlArray = endpoint.split('/')
let actualEndpoint = urlArray.shift()
let remainingUrl = urlArray.join('/')
if (!allEndpoints.hasOwnProperty(actualEndpoint)) {
allEndpoints[actualEndpoint] = {}
}
if (urlParts.search != null) {
remainingUrl += urlParts.search
}
allEndpoints[actualEndpoint][remainingUrl] = dataFile
} else {
if (!allEndpoints.hasOwnProperty(endpoint)) {
allEndpoints[endpoint] = {}
}
if (urlParts.query != null) {
allEndpoints[endpoint][urlParts.query] = dataFile
} else {
allEndpoints[endpoint][endpoint] = dataFile
}
}
return allEndpoints
}
function buildRESTRoute (data, endpointName) {
let urlPath = ''
if (endpointName === 'api') {
urlPath = '/api'
} else {
urlPath = '/api/' + endpointName + '*'
}
server.all(urlPath, function (req, res) {
const query = req.url
let endpoint = query.replace(/\/api\//, '')
let match = ''
if (endpoint === endpointName && data.hasOwnProperty(endpoint)) { // this happens when no querystring is passed
match = data[endpoint]
} else {
const querystrings = Object.keys(data).map(key => data[key])
match = lodash.find(querystrings, function (item) {
return query.includes(item.url)
})
}
if (match !== undefined) {
// TODO: DEAL WITH PARTIAL MATCHES
const jsonResponse = generateResponse(req, match)
res.json(jsonResponse)
} else {
res.sendStatus(501)
}
})
}
function generateResponse (request, data) {
let reqMethod = request.method.toLowerCase()
let requestMethodExists = data.hasOwnProperty(reqMethod)
if (requestMethodExists) {
return data[reqMethod]
} else {
return {'status': `Data was received and the http method was ${reqMethod}`, 'data': request.body}
}
}