-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.js
executable file
·89 lines (70 loc) · 2.07 KB
/
plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { GoogleLayer } from "@rabota/analytics-layer";
export default async (context, inject) => {
const pluginOptions = <%= serialize(options) %>;
const { app: { router } } = context;
let {
staticCounters = [],
dynamicCounters = [],
visitParams,
manualFirstHit = false,
firstHitVisitParams = false,
logging = false,
} = pluginOptions;
const layer = new GoogleLayer({
logging, staticCounters
});
// inject google analytics layer into context
inject( 'ga', layer );
const isAvailable = typeof window !== 'undefined' && !!window[ layer.layerName ];
if (!isAvailable) {
return;
}
// resolve all counters
dynamicCounters = await resolveCounters( dynamicCounters, context );
// set resolved dynamic counters
layer.setDynamicCounters( dynamicCounters );
// init dynamic counters
layer.init( dynamicCounters );
// subscribe to router events
let firstHit = true;
router && router.afterEach((to, from) => {
let toPath = to.fullPath;
let fromPath = from.fullPath;
const hasHitParamsFn = typeof visitParams === 'function';
const params = hasHitParamsFn && visitParams( context ) || visitParams;
if (firstHit) {
// set referer to null when the first hit
fromPath = null;
firstHit = false;
if (!manualFirstHit) {
if (firstHitVisitParams) {
// send visit params
layer.setParams( params );
}
return;
}
}
const options = {};
if (params) {
Object.assign(options, { params });
}
// send new page url with the referer to each counter
layer.hit( toPath, fromPath, options );
});
}
/**
* @param {number|string|Array<number|string>|Function} countersOrFn
* @param {*} context
* @return {Promise<Array<string|number>>}
*/
async function resolveCounters (countersOrFn, context) {
const useFn = typeof countersOrFn === 'function';
const wrappedFn = Promise.resolve(
useFn
? countersOrFn( context )
: countersOrFn
);
return wrappedFn.then(counters => {
return [].concat( counters || [] );
});
}