Something like this.
function resizeImage(req, res, next) {
lwip.open(req.file.buffer, 'jpg', function (err, img) {
if (err) return callback(err);
var image = new Image(img);
let ratio = (image.width() > 960 ? (960 / image.width()) : 1);
async.series([
image.scale.bind(image, ratio),
image.crop.bind(image, image.width(), Math.min((image.width() / 2), image.height())),
image.write.bind(image, req.params['id'], "TITLE_IMAGE", buffer, "image/jpeg")
], next);
});
}
router.post('/:id/title-image', function (req, res, next) {
resizeImage(req, res, function (err) {
if (err) res.sendStatus(400);
res.sendStatus(200);
});
});
This is just my "way" of writing things:
1. I write with 4 spaces because it lets me know when I should refactor my code into something more readable.
2. I usually move route handlers to it's own file. So it will read like
```
router.post('/:id/title-image', routes.resizeImage);
```
The idea is that routes code simply goes through the model code and send the right http status codes.
3. async is your friend :-) In general, I try to model my model APIs with async in mind.
I can give it a better shot later today if you had any comments on my first try.