-
Notifications
You must be signed in to change notification settings - Fork 52
/
app.js
251 lines (205 loc) · 6.44 KB
/
app.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/* eslint-env node, mocha */
"use strict";
var compression = require("compression");
var debug = require("debug")("apiembed");
var express = require("express");
var HTTPSnippet = require("httpsnippet");
var morgan = require("morgan");
var unirest = require("unirest");
var join = require("path").join;
module.exports = function(callback) {
var availableTargets = HTTPSnippet.availableTargets().reduce(function(
targets,
target
) {
if (target.clients) {
targets[target.key] = target.clients.reduce(function(clients, client) {
clients[client.key] = false;
return clients;
}, {});
} else {
targets[target.key] = false;
}
return targets;
},
{});
var namedTargets = HTTPSnippet.availableTargets().reduce(function(
targets,
target
) {
if (target.clients) {
targets[target.key] = target;
targets[target.key].clients = target.clients.reduce(function(
clients,
client
) {
clients[client.key] = client;
return clients;
},
{});
} else {
targets[target.key] = target;
}
return targets;
},
{});
var APIError = function(code, message) {
this.name = "APIError";
this.code = code || 500;
this.message = message || "Oops, something went wrong!";
};
APIError.prototype = Error.prototype;
// express setup
var app = express();
app.set("view engine", "pug");
app.disable("x-powered-by");
if (!process.env.NOCACHE) {
app.enable("view cache");
}
// logging
app.use(morgan("dev"));
// add 3rd party middlewares
app.use(compression());
// useful to get info in the view
app.locals.HTTPSnippet = HTTPSnippet;
app.locals.namedTargets = namedTargets;
// enable CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
// static middleware does not work here
app.use("/favicon.ico", function(req, res) {
res.sendFile(join(__dirname, "/static/favicon.ico"));
});
// static middleware does not work here
app.use("/targets", function(req, res) {
res.json(HTTPSnippet.availableTargets());
});
app.get("/", function(req, res, next) {
var source = decodeURIComponent(req.query.source);
var targets = req.query.targets || "all";
if (!source) {
return next(new APIError(400, "Invalid input"));
}
debug("received request for source: %s & targets: %s", source, targets);
// parse the requested targets
// TODO this needs optimization
var requestedTargets = targets.split(",").reduce(function(requested, part) {
var i = part.split(":");
var target = i[0] || "all";
var client = i[1] || "all";
// all targets
if (target === "all") {
// set all members to true
return Object.keys(availableTargets).reduce(function(output, current) {
if (typeof availableTargets[current] === "object") {
output[current] = Object.keys(availableTargets[current]).reduce(
function(clients, currentClient) {
clients[currentClient] = true;
return clients;
},
{}
);
} else {
output[current] = true;
}
return output;
}, {});
}
// all clients?
if (availableTargets.hasOwnProperty(target)) {
if (typeof availableTargets[target] === "object") {
if (client === "all") {
requested[target] = Object.keys(availableTargets[target]).reduce(
function(clients, currentClient) {
clients[currentClient] = true;
return clients;
},
{}
);
} else {
if (availableTargets[target].hasOwnProperty(client)) {
requested[target] = requested[target] ? requested[target] : {};
requested[target][client] = true;
}
}
} else {
requested[target] = true;
}
return requested;
}
return requested;
}, {});
unirest
.get(source)
.headers({ Accept: "application/json" })
.end(function(response) {
if (response.error) {
debug(
"failed to load source over http: %s %s",
response.code || response.error.code,
response.status || response.error.message
);
return next(new APIError(400, "Could not load JSON source"));
}
var snippet;
var output = {};
if (typeof response.body !== "object") {
try {
response.body = JSON.parse(response.body);
} catch (err) {
debug(
"failed to parse content of %s, with error: %s",
source,
err.message
);
return next(new APIError(400, "Invalid JSON source"));
}
}
try {
snippet = new HTTPSnippet(response.body);
} catch (err) {
debug("failed to generate snippet object: %s", err.message);
return next(new APIError(400, err));
}
Object.keys(requestedTargets).map(function(target) {
var outputTarget = target.replace(/\./, "_");
if (typeof requestedTargets[target] === "object") {
output[outputTarget] = {};
return Object.keys(requestedTargets[target]).map(function(client) {
var outputClient = client.replace(/\./, "_");
output[outputTarget][outputClient] = snippet.convert(target, client);
});
}
output[outputTarget] = snippet.convert(target);
});
if (Object.keys(output).length === 0) {
debug("no matching targets found");
return next(new APIError(400, "Invalid Targets"));
}
res.render("main", {
output: output
});
res.end();
});
});
// error handler
app.use(function errorHandler(error, req, res/*, next */) {
if (error.code === 400) {
error.message +=
", please review the <a href=\"https://apiembed.com/#docs\" target=\"_blank\">documentation</a> and try again";
}
// never show a 40x
res.status(200);
res.render("error", error);
});
app.listen(process.env.PORT || process.env.npm_package_config_port);
if (typeof callback === "function") {
callback();
}
};