Skip to content

Commit

Permalink
fix:trackEvent
Browse files Browse the repository at this point in the history
  • Loading branch information
omarciovsena committed Feb 15, 2024
1 parent ef3cc8e commit 6625007
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 45 deletions.
55 changes: 30 additions & 25 deletions controllers/track.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,39 @@
import ua from 'universal-analytics'

const visitor = ua(process.env.GA_TRACKING_ID)
import axios from 'axios'

const setCustomDimensions = (cd) => {
visitor.set('cd1', cd.action)
visitor.set('cd2', cd.subfeature)
visitor.set('cd3', cd.version)
visitor.set('cd4', cd.chapter)
visitor.set('cd5', cd.verse)
visitor.set('cd6', cd.ip)
visitor.set('cd7', cd.isHowToUse)
visitor.set('cd8', cd.book)
visitor.set('cd9', cd.period)
visitor.set('cd10', cd.userId)
visitor.set('uid', cd.userId)
const trackeEventGA4 = async (params) => {
const { user, category, action, label, value } = params
const { GA_MEASUREMENT_ID } = process.env

const eventData = {
client_id: user,
events: [{
name: 'request', // Nome do evento
params: {
category, action, label, value
}
}]
}

try {
await axios.post(`https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}`, eventData)
console.log({ eventData })
} catch (error) {
console.error('Erro ao enviar evento para o GA4:', error)
}
}

const generateVersesEventData = (req) => {
const { version, abbrev, chapter, number } = req.params

if (!version) {
// api/verses/search
return {
subfeature: 'search',
version: req.body.version
}
}

if (!abbrev) {
// api/verses/:version/random
return {
subfeature: 'search',
version: req.body.version
Expand Down Expand Up @@ -72,17 +77,17 @@ export const trackEvent = async (req, res, next) => {
}
const payload = actions[action] || {}

setCustomDimensions({
...payload,
const data = {
user: user ? user._id.toString() : 'anonymous',
category: 'request',
action,
ip: req.headers['x-forwarded-for'] || req.connection.remoteAddress,
isHowToUse: !!req.query.isHowToUse,
userId: user ? user._id.toString() : ''
})
label: url,
value: payload.toString()
}

return visitor.event({ ec: action, ea: 'request', el: url }, (err) => {
if (err) throw Error(err)
}).send()
await trackeEventGA4(
data
)
} catch (e) {
console.log('error: trackEvent', e)
} finally {
Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@
"mongoose": "^5.13.20",
"pug": "^3.0.2",
"redis": "^3.1.2",
"supertest": "^4.0.2",
"universal-analytics": "^0.4.23"
"supertest": "^4.0.2"
},
"devDependencies": {
"axios": "^0.21.2",
Expand All @@ -63,4 +62,4 @@
"node-mocks-http": "^1.10.1",
"nodemon": "^2.0.7"
}
}
}
18 changes: 12 additions & 6 deletions views/index.pug
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@ head
link(rel="stylesheet", href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&family=Playfair+Display:wght@700&display=swap")
link(rel='stylesheet' href='/theme-v2/css/normalize.css')
link(rel='stylesheet' href='/theme-v2/css/style.css')
script(async='' src='https://www.googletagmanager.com/gtag/js?id=#{GA_TRACKING_ID}')
script.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '#{GA_TRACKING_ID}');
link(rel='apple-touch-icon' sizes='57x57' href='/theme-v2/images/favicon/apple-icon-57x57.png')
link(rel='apple-touch-icon' sizes='60x60' href='/theme-v2/images/favicon/apple-icon-60x60.png')
link(rel='apple-touch-icon' sizes='72x72' href='/theme-v2/images/favicon/apple-icon-72x72.png')
Expand All @@ -35,8 +29,20 @@ head
meta(name='msapplication-TileColor' content='#ffffff')
meta(name='msapplication-TileImage' content='/ms-icon-144x144.png')
meta(name='theme-color' content='#ffffff')
script.
(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : '';
j.async = true;
j.src = /"https://www.googletagmanager.com/gtm.js?id=" + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', '#{GA_TRACKING_ID}');
body
// Google Tag Manager (noscript)
noscript
iframe(src='https://www.googletagmanager.com/ns.html?id=' + GA_TRACKING_ID, height='0', width='0', style='display:none;visibility:hidden')
// End Google Tag Manager (noscript)
// Fixed Navigation
nav
.container
Expand Down
13 changes: 2 additions & 11 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6064,7 +6064,7 @@ request-promise-native@^1.0.5:
stealthy-require "^1.1.1"
tough-cookie "^2.3.3"

request@^2.87.0, request@^2.88.0, request@^2.88.2:
request@^2.87.0, request@^2.88.0:
version "2.88.2"
resolved "https://registry.yarnpkg.com/request/-/request-2.88.2.tgz#d73c918731cb5a87da047e207234146f664d12b3"
integrity sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==
Expand Down Expand Up @@ -7038,15 +7038,6 @@ union-value@^1.0.0:
is-extendable "^0.1.1"
set-value "^2.0.1"

universal-analytics@^0.4.23:
version "0.4.23"
resolved "https://registry.yarnpkg.com/universal-analytics/-/universal-analytics-0.4.23.tgz#d915e676850c25c4156762471bdd7cf2eaaca8ac"
integrity sha512-lgMIH7XBI6OgYn1woDEmxhGdj8yDefMKg7GkWdeATAlQZFrMrNyxSkpDzY57iY0/6fdlzTbBV03OawvvzG+q7A==
dependencies:
debug "^4.1.1"
request "^2.88.2"
uuid "^3.0.0"

unpipe@1.0.0, unpipe@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec"
Expand Down Expand Up @@ -7115,7 +7106,7 @@ utils-merge@1.0.1:
resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713"
integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==

uuid@^3.0.0, uuid@^3.3.2:
uuid@^3.3.2:
version "3.4.0"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"
integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==
Expand Down

0 comments on commit 6625007

Please sign in to comment.