Skip to content

Commit e6f10cc

Browse files
committed
Refactors batch router
1 parent fd9e1c7 commit e6f10cc

File tree

2 files changed

+19
-19
lines changed

2 files changed

+19
-19
lines changed

src/PromiseRouter.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,19 @@ export default class PromiseRouter {
139139
this.mountOnto(expressApp);
140140
return expressApp;
141141
}
142+
143+
tryRouteRequest(method, path, request) {
144+
var match = this.match(method, path);
145+
if (!match) {
146+
throw new Parse.Error(
147+
Parse.Error.INVALID_JSON,
148+
'cannot route ' + method + ' ' + path);
149+
}
150+
request.params = match.params;
151+
return new Promise((resolve, reject) => {
152+
match.handler(request).then(resolve, reject);
153+
});
154+
}
142155
}
143156

144157
// A helper function to make an express handler out of a a promise

src/batch.js

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,39 +29,26 @@ function handleBatch(router, req) {
2929
var apiPrefixLength = req.originalUrl.length - batchPath.length;
3030
var apiPrefix = req.originalUrl.slice(0, apiPrefixLength);
3131

32-
var promises = [];
33-
for (var restRequest of req.body.requests) {
32+
let promises = req.body.requests.map((restRequest) => {
3433
// The routablePath is the path minus the api prefix
3534
if (restRequest.path.slice(0, apiPrefixLength) != apiPrefix) {
3635
throw new Parse.Error(
3736
Parse.Error.INVALID_JSON,
3837
'cannot route batch path ' + restRequest.path);
3938
}
4039
var routablePath = restRequest.path.slice(apiPrefixLength);
41-
42-
// Use the router to figure out what handler to use
43-
var match = router.match(restRequest.method, routablePath);
44-
if (!match) {
45-
throw new Parse.Error(
46-
Parse.Error.INVALID_JSON,
47-
'cannot route ' + restRequest.method + ' ' + routablePath);
48-
}
49-
50-
// Construct a request that we can send to a handler
51-
var request = {
40+
let request = {
5241
body: restRequest.body,
53-
params: match.params,
5442
config: req.config,
5543
auth: req.auth,
5644
info: req.info
57-
};
58-
59-
promises.push(match.handler(request).then((response) => {
45+
}
46+
return router.tryRouteRequest(restRequest.method, routablePath, request).then((response) => {
6047
return {success: response.response};
6148
}, (error) => {
6249
return {error: {code: error.code, error: error.message}};
63-
}));
64-
}
50+
});
51+
});
6552

6653
return Promise.all(promises).then((results) => {
6754
return {response: results};

0 commit comments

Comments
 (0)