Skip to content

Commit

Permalink
feat(web): add google analytics
Browse files Browse the repository at this point in the history
  • Loading branch information
Sikora00 authored and maciejBart99 committed Sep 15, 2020
1 parent a08b5cd commit eee2c06
Show file tree
Hide file tree
Showing 22 changed files with 229 additions and 5 deletions.
2 changes: 2 additions & 0 deletions .env-sample
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ GITLAB_CLIENT_ID=
GITLAB_CLIENT_SECRET=
GITLAB_REDIRECT_URI=

GOOGLE_ANALYTICS_ID=

#DB_HOST=db for production
DB_HOST=localhost
DB_NAME=pmp
Expand Down
32 changes: 32 additions & 0 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -2127,6 +2127,38 @@
"styleext": "scss"
}
}
},
"pmp-web-shared-util-google-analytics": {
"projectType": "library",
"root": "libs/pmp-web/shared/util-google-analytics",
"sourceRoot": "libs/pmp-web/shared/util-google-analytics/src",
"prefix": "pimp-my-pr",
"architect": {
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"libs/pmp-web/shared/util-google-analytics/tsconfig.lib.json",
"libs/pmp-web/shared/util-google-analytics/tsconfig.spec.json"
],
"exclude": ["**/node_modules/**", "!libs/pmp-web/shared/util-google-analytics/**"]
}
},
"test": {
"builder": "@nrwl/jest:jest",
"options": {
"jestConfig": "libs/pmp-web/shared/util-google-analytics/jest.config.js",
"tsConfig": "libs/pmp-web/shared/util-google-analytics/tsconfig.spec.json",
"passWithNoTests": true,
"setupFile": "libs/pmp-web/shared/util-google-analytics/src/test-setup.ts"
}
}
},
"schematics": {
"@nrwl/angular:component": {
"style": "scss"
}
}
}
},
"cli": {
Expand Down
2 changes: 2 additions & 0 deletions apps/pmp-web/docker/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ GITHUB_CLIENT_ID="${GITHUB_CLIENT_ID}"
BITBUCKET_CLIENT_ID="${BITBUCKET_CLIENT_ID}"
GITLAB_CLIENT_ID="${GITLAB_CLIENT_ID}"
GITLAB_REDIRECT_URI="${GITLAB_REDIRECT_URI}"
GOOGLE_ANALYTICS_ID="${GOOGLE_ANALYTICS_ID}"

for f in /usr/share/nginx/html/assets/env/*.sample; do
cp -- "$f" "${f%.sample}"
sed -i -- "s/{{githubClientId}}/${GITHUB_CLIENT_ID}/g" "${f%.sample}"
sed -i -- "s/{{bitbucketClientId}}/${BITBUCKET_CLIENT_ID}/g" "${f%.sample}"
sed -i -- "s/{{gitlabClientId}}/${GITLAB_CLIENT_ID}/g" "${f%.sample}"
sed -i -- "s/{{gitlabRedirectUri}}/${GITLAB_REDIRECT_URI}/g" "${f%.sample}"
sed -i -- "s/{{googleAnalyticsId}}/${GOOGLE_ANALYTICS_ID}/g" "${f%.sample}"
echo "${f%.sample}"
done

Expand Down
8 changes: 7 additions & 1 deletion apps/pmp-web/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { Component } from '@angular/core';
// tslint:disable-next-line:nx-enforce-module-boundaries @ToDo how to handle such cases
import { GoogleAnalyticsService } from '@pimp-my-pr/pmp-web/shared/util-google-analytics';

@Component({
selector: 'pmp-root',
templateUrl: './app.component.html'
})
export class AppComponent {}
export class AppComponent {
constructor(private googleAnalytics: GoogleAnalyticsService) {
this.googleAnalytics.init();
}
}
3 changes: 2 additions & 1 deletion apps/pmp-web/src/assets/env/env.json.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
"bitbucketClientId": "{{bitbucketClientId}}",
"githubClientId": "{{githubClientId}}",
"gitlabClientId": "{{gitlabClientId}}",
"gitlabRedirectUri": "{{gitlabRedirectUri}}"
"gitlabRedirectUri": "{{gitlabRedirectUri}}",
"googleAnalyticsId": "{{googleAnalyticsId}}"
}
5 changes: 5 additions & 0 deletions apps/pmp-web/src/assets/scripts/google-analytics-script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ services:
- GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID}
- GITLAB_CLIENT_ID=${GITLAB_CLIENT_ID}
- GITLAB_REDIRECT_URI=${GITLAB_REDIRECT_URI}
- GOOGLE_ANALYTICS_ID=${GOOGLE_ANALYTICS_ID}
networks:
- default
api:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ export class Environment {
githubClientId: string;
gitlabClientId: string;
gitlabRedirectUri: string;
googleAnalyticsId: string;
production: boolean;
}
7 changes: 7 additions & 0 deletions libs/pmp-web/shared/util-google-analytics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# pmp-web-shared-util-google-analytics

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test pmp-web-shared-util-google-analytics` to execute the unit tests.
10 changes: 10 additions & 0 deletions libs/pmp-web/shared/util-google-analytics/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
name: 'pmp-web-shared-util-google-analytics',
preset: '../../../../jest.config.js',
coverageDirectory: '../../../../coverage/libs/pmp-web/shared/util-google-analytics',
snapshotSerializers: [
'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
'jest-preset-angular/build/AngularSnapshotSerializer.js',
'jest-preset-angular/build/HTMLCommentSerializer.js'
]
};
1 change: 1 addition & 0 deletions libs/pmp-web/shared/util-google-analytics/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/google-analytics.service';
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { GoogleAnalyticsService } from './google-analytics.service';

describe('GoogleAnalyticsService', () => {
let service: GoogleAnalyticsService;

beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(GoogleAnalyticsService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { Inject, Injectable, Renderer2, RendererFactory2 } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { NavigationEnd, Router, RouterEvent } from '@angular/router';
import { environment } from '@pimp-my-pr/pmp-web/shared/config';
import { Observable } from 'rxjs';
import { filter, share, tap } from 'rxjs/operators';

declare let gtag: Function;

@Injectable({
providedIn: 'root'
})
export class GoogleAnalyticsService {
private readonly renderer: Renderer2;
private readonly googleId: string;
private loaded = false;
private loadingInProgress = false;

constructor(
private rendererFactory: RendererFactory2,
@Inject(DOCUMENT) private document: Document,
private router: Router
) {
this.renderer = rendererFactory.createRenderer(null, null);
this.googleId = environment.googleAnalyticsId;
}

async init(): Promise<void> {
if (this.loaded || this.loadingInProgress) return;
try {
await this.insertGoogleScript(this.googleId);
await this.insertLocalScript();
this.loaded = true;
} catch (error) {
console.error(error);
} finally {
this.loadingInProgress = false;
}
}

trackPageViews(): Observable<NavigationEnd> {
return this.router.events.pipe(
filter(() => this.loaded),
filter((evt: RouterEvent) => evt instanceof NavigationEnd),
tap((event: NavigationEnd) => {
this.trackSinglePageView(event);
}),
share()
);
}

private trackSinglePageView(event: NavigationEnd): void {
gtag('config', this.googleId, { page_path: event.urlAfterRedirects });
}

private async insertGoogleScript(googleId: string): Promise<void> {
if (!googleId) throw new Error('googleId not set');
await this.insertScript(`https://www.googletagmanager.com/gtag/js?id=${googleId}`);
}

private async insertLocalScript(): Promise<void> {
await this.insertScript('/assets/scripts/google-analytics-script.js');
}

private insertScript(path: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
const script = this.renderer.createElement('script') as HTMLScriptElement;
script.type = 'text/javascript';
script.onload = () => resolve();
script.onerror = () => reject();
script.src = path;
script.text = path;
this.renderer.appendChild(this.document.body, script);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import 'jest-preset-angular';
7 changes: 7 additions & 0 deletions libs/pmp-web/shared/util-google-analytics/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../../../tsconfig.json",
"compilerOptions": {
"types": ["node", "jest"]
},
"include": ["**/*.ts"]
}
17 changes: 17 additions & 0 deletions libs/pmp-web/shared/util-google-analytics/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../../dist/out-tsc",
"target": "es2015",
"declaration": true,
"inlineSources": true,
"types": [],
"lib": ["dom", "es2018"]
},
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"enableResourceInlining": true
},
"exclude": ["src/test-setup.ts", "**/*.spec.ts"]
}
10 changes: 10 additions & 0 deletions libs/pmp-web/shared/util-google-analytics/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
10 changes: 10 additions & 0 deletions libs/pmp-web/shared/util-google-analytics/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../../../tslint.json",
"rules": {
"directive-selector": [true, "attribute", "pimpMyPr", "camelCase"],
"component-selector": [true, "element", "pimp-my-pr", "kebab-case"]
},
"linterOptions": {
"exclude": ["!**/*"]
}
}
3 changes: 3 additions & 0 deletions nx.json
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,9 @@
},
"pmp-web-shared-styles": {
"tags": ["scope:shared", "type:styles", "platform:web"]
},
"pmp-web-shared-util-google-analytics": {
"tags": ["platform:web", "scope:shared", "type:util"]
}
},
"tasksRunnerOptions": {
Expand Down
8 changes: 7 additions & 1 deletion scripts/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ var _a = process.env,
GITHUB_CLIENT_ID = _a.GITHUB_CLIENT_ID,
BITBUCKET_CLIENT_ID = _a.BITBUCKET_CLIENT_ID,
GITLAB_CLIENT_ID = _a.GITLAB_CLIENT_ID,
GITLAB_REDIRECT_URI = _a.GITLAB_REDIRECT_URI;
GITLAB_REDIRECT_URI = _a.GITLAB_REDIRECT_URI,
GOOGLE_ANALYTICS_ID = _a.GOOGLE_ANALYTICS_ID;
function initPmpWebEnvironment() {
var environmentFile = 'apps/pmp-web/src/assets/env/env.json';
fs.copyFileSync('apps/pmp-web/src/assets/env/env.json.sample', environmentFile);
Expand All @@ -31,6 +32,11 @@ function initPmpWebEnvironment() {
'' + (GITLAB_REDIRECT_URI ? '"' + GITLAB_REDIRECT_URI + '"' : null),
[environmentFile]
);
replaceInFiles(
'"{{googleAnalyticsId}}"',
'' + (GOOGLE_ANALYTICS_ID ? '"' + GOOGLE_ANALYTICS_ID + '"' : null),
[environmentFile]
);
}
function replaceInFiles(from, to, files) {
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
Expand Down
9 changes: 8 additions & 1 deletion scripts/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ const {
GITHUB_CLIENT_ID,
BITBUCKET_CLIENT_ID,
GITLAB_CLIENT_ID,
GITLAB_REDIRECT_URI
GITLAB_REDIRECT_URI,
GOOGLE_ANALYTICS_ID
} = process.env;

function initPmpWebEnvironment(): void {
Expand All @@ -31,6 +32,12 @@ function initPmpWebEnvironment(): void {
`${GITLAB_REDIRECT_URI ? `"${GITLAB_REDIRECT_URI}"` : null}`,
[environmentFile]
);

replaceInFiles(
`"{{googleAnalyticsId}}"`,
`${GOOGLE_ANALYTICS_ID ? `"${GOOGLE_ANALYTICS_ID}"` : null}`,
[environmentFile]
);
}

function replaceInFiles(from: string, to: string, files: string[]): void {
Expand Down
5 changes: 4 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,10 @@
"@pimp-my-pr/server/auth/infrastructure-remote-token-crypto": [
"libs/server/auth/infrastructure-remote-token-crypto/src/index.ts"
],
"@pimp-my-pr/pmp-web/shared/styles": ["libs/pmp-web/shared/styles/src/index.ts"]
"@pimp-my-pr/pmp-web/shared/styles": ["libs/pmp-web/shared/styles/src/index.ts"],
"@pimp-my-pr/pmp-web/shared/util-google-analytics": [
"libs/pmp-web/shared/util-google-analytics/src/index.ts"
]
}
},
"exclude": ["node_modules", "tmp"]
Expand Down

0 comments on commit eee2c06

Please sign in to comment.