Skip to content

Commit

Permalink
fix: input validation
Browse files Browse the repository at this point in the history
  • Loading branch information
dzehnder committed Jun 18, 2024
1 parent 649dda4 commit 43cfc55
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
14 changes: 13 additions & 1 deletion packages/spacecat-shared-ahrefs-client/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* governing permissions and limitations under the License.
*/

import { isValidUrl } from '@adobe/spacecat-shared-utils';
import { hasText, isValidUrl, isArray } from '@adobe/spacecat-shared-utils';
import { context as h2, h1 } from '@adobe/fetch';

/* c8 ignore next 3 */
Expand Down Expand Up @@ -177,6 +177,18 @@ export default class AhrefsAPIClient {
}

async getOrganicKeywords(url, country = 'us', keywordFilter = [], limit = 200) {
if (!hasText(url)) {
throw new Error(`Invalid URL: ${url}`);
}
if (!hasText(country)) {
throw new Error(`Invalid country: ${country}`);
}
if (!isArray(keywordFilter)) {
throw new Error(`Invalid keyword filter: ${keywordFilter}`);
}
if (!Number.isInteger(limit) || limit < 1) {
throw new Error(`Invalid limit: ${limit}`);
}
const queryParams = {
country,
date: new Date().toISOString().split('T')[0],
Expand Down
22 changes: 21 additions & 1 deletion packages/spacecat-shared-ahrefs-client/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -374,9 +374,29 @@ describe('AhrefsAPIClient', () => {
});
});

it('throws error when keyword filter does not contain appropriate keyword items', async () => {
const result = client.getOrganicKeywords('test-site.com', 'us', [BigInt(123)]);
await expect(result).to.be.rejectedWith('Error parsing keyword filter: Do not know how to serialize a BigInt');
});

it('throws error when keyword filter is not an array', async () => {
const result = client.getOrganicKeywords('test-site.com', 'us', 'keyword1');
await expect(result).to.be.rejectedWith('Error parsing keyword filter: keywordFilter.map is not a function');
await expect(result).to.be.rejectedWith('Invalid keyword filter: keyword1');
});

it('throws error when url is not a string', async () => {
const result = client.getOrganicKeywords(123);
await expect(result).to.be.rejectedWith('Invalid URL: 123');
});

it('throws error when country is not a string', async () => {
const result = client.getOrganicKeywords('test-site.com', 123);
await expect(result).to.be.rejectedWith('Invalid country: 123');
});

it('throws error when limit is not an integer', async () => {
const result = client.getOrganicKeywords('test-site.com', 'us', [], 1.5);
await expect(result).to.be.rejectedWith('Invalid limit: 1.5');
});
});
});

0 comments on commit 43cfc55

Please sign in to comment.