-
Notifications
You must be signed in to change notification settings - Fork 411
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(contents): Integrar Umami para views de conteúdo
Integra o Umami Analytics para rastrear visualizações de conteúdo no site. re #1115
- Loading branch information
1 parent
c747083
commit 08356a2
Showing
8 changed files
with
179 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
async function get(content) { | ||
if (process.env.NEXT_PUBLIC_UMAMI_ENABLED !== 'true') { | ||
return { metrics: [] }; | ||
} | ||
|
||
if (!content || !content.created_at || !content.owner_username || !content.slug) { | ||
return { metrics: [] }; | ||
} | ||
|
||
const startAt = new Date(content.created_at).getTime(); | ||
const endAt = Date.now(); | ||
const url = `/${content.owner_username}/${content.slug}`; | ||
|
||
const params = new URLSearchParams({ | ||
startAt: String(startAt), | ||
endAt: String(endAt), | ||
url, | ||
}); | ||
|
||
try { | ||
const res = await fetch( | ||
`https://api.umami.is/v1/websites/${process.env.NEXT_PUBLIC_UMAMI_ID_WEBSITE}/stats?${params.toString()}`, | ||
{ | ||
method: 'GET', | ||
headers: { | ||
'x-umami-api-key': process.env.UMAMI_KEY, | ||
'Content-Type': 'application/json', | ||
}, | ||
}, | ||
); | ||
|
||
if (!res.ok) { | ||
return { metrics: [] }; | ||
} | ||
|
||
const data = await res.json(); | ||
|
||
const metrics = { | ||
slug: url, | ||
infos: data, | ||
}; | ||
|
||
return { metrics }; | ||
} catch (error) { | ||
return { metrics: [] }; | ||
} | ||
} | ||
|
||
export default Object.freeze({ | ||
get, | ||
}); |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
pages/api/v1/contents/[username]/[slug]/views/index.public.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import nextConnect from 'next-connect'; | ||
|
||
import { NotFoundError } from 'errors'; | ||
import cacheControl from 'models/cache-control'; | ||
import content from 'models/content'; | ||
import controller from 'models/controller'; | ||
import validator from 'models/validator'; | ||
import viewsContent from 'models/views-content'; | ||
|
||
export default nextConnect({ | ||
attachParams: true, | ||
onNoMatch: controller.onNoMatchHandler, | ||
onError: controller.onErrorHandler, | ||
}) | ||
.use(controller.injectRequestMetadata) | ||
.use(controller.logRequest) | ||
.use(cacheControl.swrMaxAge(60)) | ||
.get(getValidationHandler, getHandler); | ||
|
||
function getValidationHandler(request, response, next) { | ||
const cleanValues = validator(request.query, { | ||
username: 'required', | ||
slug: 'required', | ||
}); | ||
|
||
request.query = cleanValues; | ||
|
||
next(); | ||
} | ||
|
||
async function getHandler(request, response) { | ||
const contentFound = await content.findOne({ | ||
where: { | ||
owner_username: request.query.username, | ||
slug: request.query.slug, | ||
status: 'published', | ||
}, | ||
}); | ||
|
||
if (!contentFound) { | ||
throw new NotFoundError({ | ||
message: `Este conteúdo não está disponível.`, | ||
action: 'Verifique se o "slug" está digitado corretamente ou considere o fato do conteúdo ter sido despublicado.', | ||
stack: new Error().stack, | ||
errorLocationCode: 'CONTROLLER:CONTENT:VIEWS:GET_HANDLER:SLUG_NOT_FOUND', | ||
key: 'slug', | ||
}); | ||
} | ||
|
||
const getViews = await viewsContent.get(contentFound); | ||
|
||
response.statusCode = 200; | ||
response.setHeader('Content-Type', 'application/json'); | ||
response.end(JSON.stringify(getViews)); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import umami from '@umami/node'; | ||
import { useRouter } from 'next/router'; | ||
import { useEffect, useState } from 'react'; | ||
|
||
umami.init({ | ||
websiteId: process.env.NEXT_PUBLIC_UMAMI_ID_WEBSITE, | ||
hostUrl: 'https://cloud.umami.is', | ||
}); | ||
|
||
const isValidPageForTracking = (routerPath, validPages) => { | ||
return validPages.some((page) => routerPath.startsWith(page)); | ||
}; | ||
|
||
export default function useUmamiTracking() { | ||
const router = useRouter(); | ||
const [hasTrackedInitialPage, setHasTrackedInitialPage] = useState(false); | ||
|
||
useEffect(() => { | ||
const isUmamiEnabled = process.env.NEXT_PUBLIC_UMAMI_ENABLED === 'true'; | ||
const validPages = ['/login', '/cadastro']; | ||
const isUmamiActive = validPages.some((page) => router.asPath.startsWith(page)); | ||
|
||
const trackPageView = (url) => { | ||
if (umami) { | ||
const trackData = { | ||
url, | ||
hostname: window.location.hostname, | ||
language: window.navigator.language, | ||
screen: `${window.screen.width}x${window.screen.height}`, | ||
title: document.title, | ||
}; | ||
|
||
umami.track(trackData); | ||
} | ||
}; | ||
|
||
if (isUmamiEnabled && isUmamiActive) { | ||
if (isValidPageForTracking(router.asPath, validPages) && !hasTrackedInitialPage) { | ||
trackPageView(router.asPath); | ||
setHasTrackedInitialPage(true); | ||
} | ||
|
||
const handleRouteChange = (url) => { | ||
if (isValidPageForTracking(url, validPages)) { | ||
trackPageView(url); | ||
} | ||
}; | ||
|
||
router.events.on('routeChangeComplete', handleRouteChange); | ||
|
||
return () => { | ||
router.events.off('routeChangeComplete', handleRouteChange); | ||
}; | ||
} | ||
}, [router.asPath, hasTrackedInitialPage, router.events]); | ||
|
||
return null; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters