forked from scriptex/localga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (52 loc) · 1.44 KB
/
index.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
/**
* External dependencies
*/
const request = require('request-promise-native');
/**
* Internal dependencies
*/
const { writeFileSync, unlinkSync, existsSync } = require('fs');
/**
* Google analytics root url
*/
const FILE_NAME = 'google-analytics-local.js';
const GA_SCRIPT_URL = 'https://www.googletagmanager.com/gtag/js';
const ANALYTICS_FILE_NAME = 'analytics.js';
const ANALYTICS_SCRIPT_URL = `https://www.google-analytics.com/${ANALYTICS_FILE_NAME}`;
const saveFile = (file, data) => {
if (existsSync(file)) {
unlinkSync(file);
}
writeFileSync(file, data);
};
const saveAnalyticsFile = folder => {
const file = `${folder}/${ANALYTICS_FILE_NAME}`;
return request(ANALYTICS_SCRIPT_URL)
.then(data => saveFile(file, data))
.catch(console.error);
};
/**
* Generate local version of google analytics script
*
* @param {Object} options
*
* @return {Void}
*/
const localga = options => {
const { id, folder } = options;
const file = `${folder}/${FILE_NAME}`;
if (!id) {
throw new Error('No google analytics ID supplied.');
}
return request(`${GA_SCRIPT_URL}?id=${id}`)
.then(async data => {
data = data.replace(ANALYTICS_SCRIPT_URL, `${folder}/${ANALYTICS_FILE_NAME}`);
saveFile(file, data);
await saveAnalyticsFile(folder);
})
.catch(console.error);
};
module.exports = localga;
module.exports.localga = localga;
module.exports.FILE_NAME = FILE_NAME;
module.exports.ANALYTICS_FILE_NAME = ANALYTICS_FILE_NAME;