Skip to content

Commit

Permalink
Follow redirects (#789)
Browse files Browse the repository at this point in the history
* Follow redirects

Fixes #775

* Follow redirects

Fixing lint error

* Follow redirects

Fix tests

* Added redirect test

* Fixed lint errors

* Skip redirect test in browser as we cannot mock a server

* Different test for browser

* Fixed browser detection
  • Loading branch information
SaWey authored and hipstersmoothie committed Nov 26, 2019
1 parent c6f1142 commit c3835b2
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/core/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ function loadFromURL(options, cb) {
if (err) {
return cb(err);
}

if('headers' in response && 'location' in response.headers){
options.url = response.headers.location;
return loadFromURL(options, cb);
}

if (typeof data === 'object' && Buffer.isBuffer(data)) {
return cb(null, data);
Expand Down
Binary file added packages/core/test/images/pixel.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
57 changes: 57 additions & 0 deletions packages/core/test/redirect.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Jimp as jimp, getTestDir } from '@jimp/test-utils';

const fs = require('fs');
const http = require('http');

const imagesDir = getTestDir(__dirname) + '/images';

const httpHandler = (req, res) => {
switch (req.method) {
case 'GET':
switch (req.url) {
case '/redirect.png':
res.writeHead(301, {
Location: 'http://localhost:5136/corrected.png'
});
res.end();
break;
case '/corrected.png':
res.writeHead(200, { 'Content-Type': 'image/png' });
res.end(fs.readFileSync(imagesDir + '/pixel.png'), 'binary');
break;
default:
res.writeHead(404);
res.end('Not a valid test endpoint');
break;
}
break;
default:
res.writeHead(404);
res.end('Invalid request method');
break;
}
};

describe('redirect', function() {
if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
xit('Not testing redirects in browser');
} else {
const httpServer = http.createServer(httpHandler);
before(function() {
httpServer.listen(5136);
});

it('follows 301 redirect', function(done) {
jimp
.read('http://localhost:5136/redirect.png')
.then(() => {
httpServer.close();
done();
})
.catch(error => {
httpServer.close();
done(error);
});
});
}
});

0 comments on commit c3835b2

Please sign in to comment.