Skip to content

Commit

Permalink
feat(sdk-analytics) comments done
Browse files Browse the repository at this point in the history
  • Loading branch information
oidacra committed Dec 17, 2024
1 parent 516501d commit 9d616de
Show file tree
Hide file tree
Showing 21 changed files with 464 additions and 134 deletions.
20 changes: 7 additions & 13 deletions core-web/libs/sdk/analytics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Or include the script in your HTML page:
First, import the provider:

```tsx
import { DotContentAnalyticsProvider } from '@dotcms/analytics';
import { DotContentAnalyticsProvider } from '@dotcms/analytics/react';
```

Wrap your application with the `DotContentAnalyticsProvider`:
Expand All @@ -56,21 +56,15 @@ function App() {
Use the `useAnalyticsTracker` hook to track custom events:

```tsx
import { useAnalyticsTracker } from '@dotcms/analytics/react';

function Activity({ title, urlTitle }) {
const { track } = useAnalyticsTracker();

const handleClick = () => {
// First parameter: custom event name to identify the action
// Second parameter: object with properties you want to track
track('product-detail-click', {
productTitle: title,
productUrl: urlTitle,
clickedElement: 'detail-button',
timestamp: new Date().toISOString()
});
};

return <button onClick={handleClick}>See Details →</button>;
// First parameter: custom event name to identify the action
// Second parameter: object with properties you want to track

return <button onClick={() => track('btn-click', { title, urlTitle })}>See Details →</button>;
}
```

Expand Down
9 changes: 5 additions & 4 deletions core-web/libs/sdk/analytics/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@ if (swcJestConfig.swcrc === undefined) {
// Uncomment if using global setup/teardown files being transformed via swc
// https://nx.dev/nx-api/jest/documents/overview#global-setupteardown-with-nx-libraries
// jest needs EsModule Interop to find the default exported setup/teardown functions
// swcJestConfig.module.noInterop = false;
swcJestConfig.module.noInterop = false;

export default {
displayName: 'analytics',
preset: '../../../jest.preset.js',
transform: {
'^.+\\.[tj]s$': ['@swc/jest', swcJestConfig]
'^.+\\.[tj]sx?$': ['@swc/jest', swcJestConfig]
},
moduleFileExtensions: ['ts', 'js', 'html'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
testEnvironment: 'jsdom',
coverageDirectory: '../../../coverage/libs/sdk/analytics'
coverageDirectory: '../../../coverage/libs/sdk/analytics',
setupFilesAfterEnv: ['<rootDir>/test-setup.ts']
};
7 changes: 4 additions & 3 deletions core-web/libs/sdk/analytics/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"homepage": "https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/analytics/README.md",
"dependencies": {
"analytics": "^0.8.14",
"vite": "~5.0.0"
"vite": "~5.0.0",
"@testing-library/jest-dom": "^6.1.6"
},
"peerDependencies": {
"react": "^18.2.0"
Expand All @@ -31,8 +32,8 @@
"module": "./index.esm.js",
"exports": {
"./react": {
"import": "./lib/react/index.js",
"types": "./lib/react/index.d.ts"
"import": "./react/index.js",
"types": "./src/lib/react/index.d.ts"
}
}
}
5 changes: 0 additions & 5 deletions core-web/libs/sdk/analytics/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,6 @@
"project": "libs/sdk/analytics/package.json"
}
},
"nx-release-publish": {
"options": {
"packageRoot": "dist/{projectRoot}"
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
import Analytics from 'analytics';

import { DotContentAnalytics } from './dot-content-analytics';
import { dotAnalyticsPlugin } from './plugin/dot-analytics.plugin';
import { dotAnalytics } from './plugin/dot-analytics.plugin';
import { DotContentAnalyticsConfig } from './shared/dot-content-analytics.model';

// Mock the analytics library
jest.mock('analytics');
jest.mock('./plugin/dot-analytics.plugin');

describe('DotAnalytics', () => {
const mockConfig = {
const mockConfig: DotContentAnalyticsConfig = {
debug: false,
server: 'http://test.com',
key: 'test-key',
apiKey: 'test-key',
autoPageView: false
};

Expand Down Expand Up @@ -43,17 +44,34 @@ describe('DotAnalytics', () => {
it('should initialize analytics with correct config', async () => {
const instance = DotContentAnalytics.getInstance(mockConfig);
const mockAnalytics = {};

(Analytics as jest.Mock).mockReturnValue(mockAnalytics);
(dotAnalyticsPlugin as jest.Mock).mockReturnValue({ name: 'mock-plugin' });
(dotAnalytics as jest.Mock).mockReturnValue({ name: 'mock-plugin' });

// Mock del enricher plugin
jest.mock('./plugin/dot-analytics.enricher.plugin', () => ({
dotAnalyticsEnricherPlugin: {
name: 'enrich-dot-analytics',
'page:dot-analytics': jest.fn(),
'track:dot-analytics': jest.fn()
}
}));

await instance.ready();

expect(Analytics).toHaveBeenCalledWith({
app: 'dotAnalytics',
debug: false,
plugins: [{ name: 'mock-plugin' }]
plugins: [
{
name: 'enrich-dot-analytics',
'page:dot-analytics': expect.any(Function),
'track:dot-analytics': expect.any(Function)
},
{ name: 'mock-plugin' }
]
});
expect(dotAnalyticsPlugin).toHaveBeenCalledWith(mockConfig);
expect(dotAnalytics).toHaveBeenCalledWith(mockConfig);
});

it('should only initialize once', async () => {
Expand All @@ -72,20 +90,20 @@ describe('DotAnalytics', () => {
throw error;
});

// eslint-disable-next-line @typescript-eslint/no-empty-function
const consoleErrorMock = jest.spyOn(console, 'error').mockImplementation(() => {});
const consoleErrorMock = jest.spyOn(console, 'error').mockImplementation(() => {
// Do nothing
});

try {
await instance.ready();
fail('Should have thrown an error');
} catch (e) {
expect(e).toEqual(error);
expect(console.error).toHaveBeenCalledWith(
'Failed to initialize DotAnalytics:',
error
'[dotCMS DotContentAnalytics] Failed to initialize: Error: Init failed'
);
}

// Restore console.error
consoleErrorMock.mockRestore();
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { DotContentAnalyticsConfig, ServerEvent } from './dot-content-analytics.
export const sendAnalyticsEventToServer = async (
data: Record<string, unknown>,
options: DotContentAnalyticsConfig
): Promise<Response> => {
): Promise<void> => {
const serverEvent: ServerEvent = {
...data,
timestamp: new Date().toISOString(),
Expand All @@ -28,13 +28,10 @@ export const sendAnalyticsEventToServer = async (
body: JSON.stringify(serverEvent)
});

if (response.ok) {
return response;
} else {
throw new Error(`${response.status}`);
if (!response.ok) {
console.error(`DotAnalytics: Server responded with status ${response.status}`);
}
} catch (error) {
console.error('DotAnalytics: Error sending event:', error);
throw error;
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export interface DotContentAnalyticsConfig {
/**
* Automatically track page views when set to true.
*/
autoPageView: boolean;
autoPageView?: boolean;

/**
* The API key for authenticating with the Analytics service.
Expand Down
Loading

0 comments on commit 9d616de

Please sign in to comment.