javascript Subclass node.js express methods to add common functionality?
Sorry, still reasonably new to Javascript here, so hope this question isn't too embarrassingly easy, but:
I'm finding I'm writing a lot of code in node.js (express) along the following lin开发者_开发技巧es:
app.get("urlscheme1", function (res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_taskABC();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
});
app.put("urlscheme1", function (res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_taskDEF();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
});
app.post("urlscheme1", function (res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_taskGHI();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
});
This seems HORRIBLY wasteful. But, I'm not 100% comfortable with all the prototype
and "subclassing" syntax/semantics in JS enough yet to understand how to make this better. Is there some way to extend an existing class (express app in this instance) to let me do something like:
app.get("urlscheme1", function(res, resp) {
do_something_ABC();
});
app.get("urlscheme1", function(res, resp) {
do_something_DEF();
});
app.get("urlscheme1", function(res, resp) {
do_something_GHI();
});
where all of these handler functions are still executing that "common" code?
Thanks!
Something like this would work:
function install(urlscheme, method, specific_task) {
function handler(res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_task();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
}
app[method](urlscheme,handler); // app.post(), app.get(), etc.
};
install("urlscheme1","get", do_something_ABC );
install("urlscheme1","post", do_something_DEF );
install("urlscheme1","put", do_something_GHI );
精彩评论