-
Notifications
You must be signed in to change notification settings - Fork 7
/
PromiseMiddleware.js
49 lines (43 loc) · 1.48 KB
/
PromiseMiddleware.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
module.exports = function (Promise, BaseMiddleware) {
class PromiseMiddleware extends BaseMiddleware {
configure(app) {
super.configure(app);
this.app.response.jsonAsync = function (...args) {
return Promise.all(args)
.then((results) => this.json.apply(this, results))
.catch(this.req.next);
};
this.app.response.renderAsync = function (view, properties) {
return Promise.props(properties ?? {})
.then((props) => this.render(view, props))
.catch(this.req.next);
};
this.app.response.sendAsync = function (...args) {
return Promise.all(args)
.then((results) => this.send.apply(this, results))
.catch(this.req.next);
};
this.app.response.sendStatusAsync = function (...args) {
return Promise.all(args)
.then((results) => this.sendStatus(results[0].status))
.catch(this.req.next);
};
this.app.response.formatAsync = function (documentKey, potentialPromise) {
return Promise.cast(potentialPromise)
.then((results) => {
this.format({
html: () => {
this.type('text/javascript');
this.send(`document.${documentKey} = ${JSON.stringify(results)};`);
},
json: () => {
this.json(results);
},
});
})
.catch(this.req.next);
};
}
}
return new PromiseMiddleware();
};