Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Fixed metric payload, updated github actions and tests #29

Merged
merged 6 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/sixty-pets-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
5 changes: 5 additions & 0 deletions .changeset/tidy-cobras-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'client-analytics': patch
---

Fixed metric payload
6 changes: 3 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Version 🔖
on:
push:
branches:
- main
- master

concurrency: ${{ github.workflow }}-${{ github.ref }}

Expand All @@ -25,9 +25,9 @@ jobs:
- name: "Setup"
uses: ./.github/actions/setup

- name: Build
- name: Install
shell: bash
run: yarn build
run: yarn

- name: Set deployment token
run: npm config set '//registry.npmjs.org/:_authToken' "${{ secrets.NPM_TOKEN }}"
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
name: Node.js CI
on:
push:
branches: ['main']
branches: ['master']
pull_request:
branches: ['main']
branches: ['master']
jobs:
build:
runs-on: ubuntu-latest
Expand Down
6 changes: 6 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

# yarn lint and added to git
yarn format:fix
git add .
5 changes: 5 additions & 0 deletions .husky/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

# make sure to run yarn test before pushing
yarn test
16 changes: 3 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
],
"scripts": {
"dev": "vite",
"typecheck": "tsc --noEmit",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest run",
Expand All @@ -25,7 +26,8 @@
"format:fix": "prettier . --write",
"release:check": "changeset status --verbose --since=origin/master",
"release:publish": "yarn install && yarn build && changeset publish",
"release:version": "changeset version && yarn install --lockfile-only"
"release:version": "changeset version && yarn install --lockfile-only",
"release:add": "changeset add"
},
"devDependencies": {
"@changesets/changelog-github": "^0.4.8",
Expand All @@ -49,18 +51,6 @@
"vite-plugin-dts": "^3.6.4",
"vitest": "^1.0.1"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"pre-push": "yarn test"
}
},
"lint-staged": {
"*.{ts,json,md}": [
"prettier --write",
"git add"
]
},
"dependencies": {
"@types/react-router": "^5.1.20",
"md5": "^2.3.0",
Expand Down
61 changes: 53 additions & 8 deletions src/storage/location.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,21 @@ import {
setPageviewConfig,
uaaValuesFromUrl,
} from '../storage/location';
import { describe, test, expect, beforeEach } from 'vitest';
import { describe, test, expect, beforeEach, afterEach } from 'vitest';
import { DEFAULT_LOCATION } from '../storage/location';

const resetState = () => {
const location = getLocation();
location.breadcrumbs = [];
location.initialUAAData = {};
location.pagePath = '';
location.prevPagePath = '';
setLocation({
breadcrumbs: [],
initialUAAData: {},
pagePath: '',
prevPagePath: '',
pageviewConfig: {
isEnabled: false,
blacklistRegex: [],
},
history: undefined,
});
};

describe('location', () => {
Expand All @@ -35,6 +41,15 @@ describe('location', () => {
});
});

test('should return the same value when called multiple times', () => {
expect(getLocation()).toBe(getLocation());
const location = getLocation();
setLocation({ breadcrumbs: [{ label: 'test', href: 'test' }] });
expect(location).toBe(getLocation());
setLocation(DEFAULT_LOCATION);
expect(location).toBe(getLocation());
});

test('should init with right values', () => {
const location = createLocation();
expect(location).toEqual({
Expand Down Expand Up @@ -71,6 +86,7 @@ describe('location', () => {

test('should set breadcrumbs with custom values', () => {
const location = getLocation();
expect(location).toEqual(DEFAULT_LOCATION);
setBreadcrumbs([
{
label: 'test',
Expand Down Expand Up @@ -105,6 +121,10 @@ describe('location', () => {
});

describe('getDocumentReferrer()', () => {
beforeEach(() => {
resetState();
});

test('should return string when document.referrer is undefined', () => {
expect(getDocumentReferrer()).toBe('');
});
Expand All @@ -122,6 +142,10 @@ describe('location', () => {
});

describe('getReferrerData()', () => {
beforeEach(() => {
setLocation(DEFAULT_LOCATION);
});

test('should return an empty object when document.referrer is an empty string', () => {
expect(getReferrerData()).toEqual({});
});
Expand All @@ -146,6 +170,10 @@ describe('location', () => {
});

describe('getUrlHostname()', () => {
beforeEach(() => {
resetState();
});

test('should return string when global.location is undefined', () => {
expect(getUrlHostname()).toBe('');
});
Expand All @@ -160,6 +188,10 @@ describe('location', () => {
});

describe('getUrlParams()', () => {
beforeEach(() => {
resetState();
});

test('should return empty string when global.location is undefined', () => {
expect(getUrlParams()).toBe('');
});
Expand All @@ -173,6 +205,13 @@ describe('location', () => {
});

describe('uaaValuesFromUrl', () => {
beforeEach(() => {
setLocation(DEFAULT_LOCATION);
});

afterEach(() => {
setLocation(DEFAULT_LOCATION);
});
test('returns UAA values', () => {
Object.defineProperty(window, 'location', {
value: { search: '?&utm_term=some-new-value' },
Expand All @@ -183,7 +222,10 @@ describe('location', () => {

describe('pageviewConfig', () => {
beforeEach(() => {
resetState();
setLocation(DEFAULT_LOCATION);
});

afterEach(() => {
setLocation(DEFAULT_LOCATION);
});

Expand Down Expand Up @@ -214,7 +256,10 @@ describe('location', () => {
});
});

test.only('modifying pageViewConfig should not touch location properties', () => {
test('modifying pageViewConfig should not touch location properties', () => {
let location = getLocation();

expect(location).toEqual(DEFAULT_LOCATION);
setLocation({
breadcrumbs: [{ label: 'test', href: 'test' }],
initialUAAData: { utm_term: 'test' },
Expand Down
14 changes: 6 additions & 8 deletions src/storage/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,18 @@ const UAA_QUERIES: AnalyticsQueries[] = [
];

export function setBreadcrumbs(breadcrumbs: Breadcrumb[]) {
const location = getLocation();
Object.assign(location, { breadcrumbs });
setLocation({ breadcrumbs });
}

export function setPageviewConfig(pageviewConfig: PageviewConfig) {
const location = getLocation();
Object.assign(location, { pageviewConfig });
setLocation({ pageviewConfig });
}

export function setLocation(data: SetLocation) {
const location = getLocation();
Object.assign(location, data);
// console.log('setLocation before', location, data);
Object.assign(location, structuredClone(data));
// console.log('setLocation after', location);
}

export const getUrlParams = (): string => {
Expand Down Expand Up @@ -213,7 +213,5 @@ export const setLocationTracking = (options: LocationHistoryTracking) => {

// TODO: we could pass the history object as an input
export const createLocation = (): Location => {
return {
...DEFAULT_LOCATION,
};
return structuredClone(DEFAULT_LOCATION);
};
20 changes: 2 additions & 18 deletions src/storage/networkLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,23 +104,7 @@ describe('networkLayer', () => {
.mockImplementation(() => 'apiFetch');
});

test('should call apiFetch when skipScheduler is set to true', async () => {
setConfig({
platform: 'unknown',
projectName: 'testProjectName',
apiEndpoint: 'https://cca-lite.coinbase.com',
});
sendMetrics(metrics, true);
expect(apiFetchSpy).toHaveBeenCalledTimes(1);
expect(configOnErrorSpy).toHaveBeenCalledTimes(0);
expect(apiFetchSpy).toHaveBeenCalledWith({
url: 'https://cca-lite.coinbase.com/metrics',
data: { metricData: JSON.stringify(metrics) },
onError: config.onError,
});
});

test('should call apiFetch when skipScheduler is false', async () => {
test('should call apiFetch', async () => {
setConfig({
platform: 'unknown',
projectName: 'testProjectName',
Expand All @@ -131,7 +115,7 @@ describe('networkLayer', () => {
expect(configOnErrorSpy).toHaveBeenCalledTimes(0);
expect(apiFetchSpy).toHaveBeenCalledWith({
url: 'https://cca-lite.coinbase.com/metrics',
data: { metricData: JSON.stringify(metrics) },
data: { metrics: metrics },
onError: config.onError,
});
});
Expand Down
24 changes: 7 additions & 17 deletions src/storage/networkLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,29 +93,19 @@ export const sendEvents = (events: Event[]) => {
});
};

export const sendMetrics = (metrics: Metric[], skipScheduler = false) => {
export const sendMetrics = (metrics: Metric[]) => {
const { apiEndpoint, metricPath, onError } = getConfig();
const metricEndpoint = `${apiEndpoint}${metricPath}`;

const data = {
metricData: JSON.stringify(metricNameEnhancer(metrics)),
metrics: metricNameEnhancer(metrics),
};

if (skipScheduler) {
apiFetch({
url: metricEndpoint,
data,
onError: onError,
});
} else {
scheduleEvent(() => {
apiFetch({
url: metricEndpoint,
data,
onError: onError,
});
});
}
apiFetch({
url: metricEndpoint,
data,
onError: onError,
});
};

// TODO: network layer should be generic as the scheduler
Expand Down
Loading