This repository has been archived by the owner on Jun 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
102 lines (93 loc) · 2.81 KB
/
index.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
import { google } from 'googleapis';
import { GAGetPostsResponse, GAGetPostsDetail } from '../../ts-api';
import { PostsQueryParams } from '../../models/posts';
import { getPrivKeyFormatted } from '../../utils';
export class gaService {
static getPosts = async (params: PostsQueryParams) => {
const gaJWTAuth = new google.auth.JWT(
process.env.GA_CLIENT_EMAIL,
undefined,
getPrivKeyFormatted(process.env.GA_PRIVATE_KEY as string),
['https://www.googleapis.com/auth/analytics.readonly'],
);
try {
const analyticsReporting = google.analyticsreporting({
version: 'v4',
auth: gaJWTAuth,
});
const result = await analyticsReporting.reports.batchGet({
requestBody: {
reportRequests: [
{
viewId: 'ga:00000000',
dateRanges: [
{
startDate: params['days-prev'],
endDate: 'today',
},
],
metrics: [
{
expression: 'ga:pageviews',
},
],
dimensions: [
{
name: 'ga:pagePath',
},
{
name: 'ga:pageTitle',
},
],
orderBys: [
{
sortOrder: 'DESCENDING',
fieldName: 'ga:pageviews',
},
],
/*
Comment or update the dimensionFilterClauses array otherwise it will only show results
where path contains slug /blog/
*/
dimensionFilterClauses: [
{
filters: [
{
dimensionName: 'ga:pagePath',
operator: 'REGEXP',
expressions: ['/blog/'],
},
],
},
],
pageSize: params.top,
},
],
},
});
const data = result.data.reports![0].data;
const posts = data!.rows!.map((post) => {
const { dimensions, metrics } = post;
const path = dimensions![0];
const title = dimensions![1];
// const views = metrics![0].values![0];
return [path, title];
});
const gaGetPostsDetail: GAGetPostsDetail = {
// totalsForAllResults: data?.totals![0].values![0],
rows: posts,
};
return {
isSuccess: true,
type: 'getPosts',
body: gaGetPostsDetail,
} as GAGetPostsResponse;
} catch (err) {
return {
isSuccess: false,
type: 'getPosts',
body: 'Error retrieving data from Google Analytics. Call for help',
} as GAGetPostsResponse;
}
};
}