forked from jhonderson/actual-http-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (54 loc) · 2.22 KB
/
Copy pathserver.js
File metadata and controls
66 lines (54 loc) · 2.22 KB
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
const { config } = require('./src/config/config');
const express = require('express');
const yaml = require('js-yaml');
const v1Routes = require("./src/v1/routes");
const app = express();
app.use(express.json());
app.use("/v1", v1Routes);
// Catch-all error handler
app.use(function(err, req, res, next) {
console.log('Internal server error:', err);
res.status(err.status || 500).json({"error": "Internal server error"});
});
const swaggerUi = require('swagger-ui-express');
const { openapiSpecification } = require('./src/config/swagger');
app.use('/api-docs', swaggerUi.serve);
// Workaround to allow user to download swagger.json file
app.get('/api-docs', swaggerUi.setup(null, {
swaggerOptions: {
url: '/api-docs/swagger.json'
}
}));
app.get('/api-docs/swagger.json', (req, res) => res.json(openapiSpecification));
app.get('/api-docs/swagger.yaml', (req, res) => {
res.type('yaml').send(yaml.dump(openapiSpecification));
});
app.listen(config.port, () => {
console.log("Actual HTTP Server Listening on PORT: ", config.port);
});
/**
* Errors generated by @actual-app/api library make the server crash.
* This can be problematic for the HTTP api since a normal behaviour such as looking
* for an nonexisting account would make the app crash. Preventing this by capturing
* the unhandled rejection errors and ignoring them if they come from @actual-app/api
*/
function ignoreUnhandledRejectionsCausedByActualApiLibrary(reason, promise) {
if (isErrorComingFromActualApi(reason) && !doesActualErrorRequiresRestartingTheHttpService(reason)) {
console.log('Ignoring unhandledRejection caused by Actual api library');
return;
}
console.log('unhandledRejection', reason);
process.exit(1);
}
function isErrorComingFromActualApi(reason) {
return reason
&& ((reason.stack && reason.stack.indexOf('@actual-app/api') != -1) || reason.type == 'APIError');
}
/**
* Forcing a restart if there is a problem opening a budget that was successfully
* opened before.
*/
function doesActualErrorRequiresRestartingTheHttpService(reason) {
return reason && reason.stack && reason.stack.indexOf('We had an unknown problem opening') != -1;
}
process.on('unhandledRejection', ignoreUnhandledRejectionsCausedByActualApiLibrary);