Fixed adding same redirect multiple times throws an error on removal (#379)

refs https://ghost.slack.com/archives/C02G9E68C/p1647599592576139

When you add a redirect multiple times, and remove it afterwards, an error is thrown:
`Cannot destructure property 'fromRegex' of 'this.redirects[redirectId]' as it is undefined.` 
This was caused by `redirectIds` that contained the same id multiple times.

* Added a test for adding a redirect multiple times and removing it once
* Fixed adding same redirect multiple times throws an error on removal
This commit is contained in:
Simon Backx 2022-03-24 09:54:19 +01:00 committed by GitHub
parent 84bbcbb057
commit 7e556d84de
2 changed files with 20 additions and 1 deletions

View File

@ -97,7 +97,10 @@ class DynamicRedirectManager {
const fromRegex = this.buildRegex(from);
const redirectId = from;
this.redirectIds.push(redirectId);
if (!this.redirectIds.includes(redirectId)) {
this.redirectIds.push(redirectId);
}
this.redirects[redirectId] = {
fromRegex,
to,

View File

@ -76,6 +76,22 @@ describe('DynamicRedirectManager', function () {
should.equal(location, null);
});
it('Can add same redirect multiple times and remove it once', function () {
manager.addRedirect('/test-params', '/result?q=abc', {permanent: true});
const id = manager.addRedirect('/test-params', '/result?q=abc', {permanent: true});
manager.removeRedirect(id);
req.url = '/test-params/?q=123&lang=js';
manager.handleRequest(req, res, function next() {
should.ok(true, 'next should have been called');
});
should.equal(headers, null);
should.equal(status, null);
should.equal(location, null);
});
it('The routing works when passed an invalid regexp for the from parameter', function () {
const from = '/invalid_regex/(/size/[a-zA-Z0-9_-.]*/[a-zA-Z0-9_-.]*/[0-9]*/[0-9]*/)([a-zA-Z0-9_-.]*)';
const to = '/';