Skip to content

Commit

Permalink
feat: modify analytics
Browse files Browse the repository at this point in the history
Today a user can test multiple files/directories by using the command `snyk {product} test {path1} {path2}`.

When doing so we are saving some of the analytics incorrectly, some examples:
`"iac-test-count": [1,2],` (should be a numeric value and not an array)
`"packageManager": ["cloudformationconfig",["terraformconfig","cloudformationconfig"]],` (shouldn't be a nested array)
Those are some IaC examples but the problem is shared across all products.

Objects should probably be handled in [registry](https://github.com/snyk/registry/blob/cdc684900ca34379eedb823e5fe0c0deff4b39d1/src/lib/analytics/cli.ts#L200) by each team separately.
  • Loading branch information
YairZ101 committed Jan 25, 2022
1 parent 3acc02f commit 0414ff9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/lib/analytics/index.ts
Expand Up @@ -98,7 +98,7 @@ async function postAnalytics(
}

/**
* Adds a key-value pair to the analytics data `metadata` field. This doesn't send the analytis, just stages it for
* Adds a key-value pair to the analytics data `metadata` field. This doesn't send the analytics, just stages it for
* sending later (via the {@link addDataAndSend} function).
* @param key
* @param value
Expand All @@ -107,11 +107,18 @@ export function add(key: string, value: unknown): void {
if (typeof value === 'string') {
value = stripAnsi(value);
}

if (metadata[key]) {
if (!Array.isArray(metadata[key])) {
metadata[key] = [metadata[key]];
if (typeof value === 'number' && typeof metadata[key] === 'number') {
metadata[key] += value;
} else {
if (!Array.isArray(metadata[key])) {
metadata[key] = [metadata[key]];
}
Array.isArray(value)
? metadata[key].push(...value)
: metadata[key].push(value);
}
metadata[key].push(value);
} else {
metadata[key] = value;
}
Expand Down
23 changes: 23 additions & 0 deletions test/jest/unit/lib/analytics/index.spec.ts
Expand Up @@ -36,4 +36,27 @@ describe('analytics module', () => {

await expect(result).resolves.toBeUndefined();
});

it('adds a value to the current analytics metadata', async () => {
const requestSpy = jest.spyOn(request, 'makeRequest');
requestSpy.mockResolvedValue();

analytics.add('k2', 2);
analytics.add('k3', { test: 'test' });
analytics.add('k1', 'v2');
analytics.add('k1', ['v3', 'v4']);
analytics.add('k1', 5);
analytics.add('k2', 4);
analytics.add('k3', { test: 'test' });

await analytics.addDataAndSend({
args: argsFrom({}),
});

expect(requestSpy.mock.calls[0][0].body.data).toHaveProperty('metadata', {
k1: ['v1', 'v2', 'v3', 'v4', 5], //v1 was added in the 1st test
k2: 6,
k3: [{ test: 'test' }, { test: 'test' }],
});
});
});

0 comments on commit 0414ff9

Please sign in to comment.