Picking up from last weekend, we're finishing the front end aspect of the project with a JavaScript visitor counter.
- Knowledge of APIs
- Experience with JavaScript
- Now that the CloudFront cache has been invalidated, this will allow a visitor counter to increment (and be displayed to the client) in real-time.
- This, looked promising. Other, simpler solutions are available
- Read the docs and choose a way of implementing
- Create a new feature branch in the source code
- Create a new JavaScript file,
counter.js
- At the bottom of
index.html
,, just before the closing</body>
tag:<script src="/js/counter.js"></script>
- Wherever you want to display the counter:
<p>You are visitor #<span id="visits">0</span></p>
- In
counter.js
:
const count = document.getElementById('visits');
updateVisitCount();
function updateVisitCount() {
fetch('https://api.countapi.xyz/update/domainname/?amount=1')
.then(res => res.json())
.then(res => {
count.innerHTML = res.value;
});
}
// The empty string below will link to a future DynamoDB database, via API Gateway
// xhttp.open(
// 'GET',
// '',
// true
// );
// xhttp.send();
Until I've actually created the backend with Lambda and DynamoDB I have no idea which solution works best. However, I'd like to avoid as many superfluous API calls as possible, and this seems like a better solutuion (if I can get it to work...). I'm also concerned that the API above acts like a database for the total visitor count, circumnavigating the whole backend?
const count = document.getElementById('visits');
updateVisitCount();
function updateVisitCount() {
fetch('put api gateway link here', {
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
},
})
.then(res => res.json())
.then(res => {
count.innerHTML = res.value;
});
}
-
Front end is displaying a hardcoded version of the visitor counter (no database to store a total in yet)
-
I have a couple of ways to link this to the future back end in
counter.js
. Hope the difference between the two makes more sense by then...
It's Christmas, it's time to build the back end with SAM CLI!