Skip to content

Commit

Permalink
🚀 Miscellaneous Refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
Ovi committed May 6, 2023
1 parent a2b2bef commit 3937ccb
Show file tree
Hide file tree
Showing 10 changed files with 142 additions and 46 deletions.
5 changes: 5 additions & 0 deletions config/dev.env
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
NODE_ENV=development
FRONTEND_URL=https://dummyjson.com
JWT_SECRET=A_VERY_SECRET_KEY
# MONGODB_URI=""
# MONGODB_DB_NAME=""
# GOOGLE_TAG_ID=""
# GOOGLE_PUBLISHER_ID=""
# GOOGLE_ADS_TXT_CONTENT=""
6 changes: 2 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const routes = require('./src/routes');
const { validateEnvVar, loadDataInMemory } = require('./src/utils/util');
const { version } = require('./package.json');

const { PORT = 3123, NODE_ENV } = process.env;
const { PORT = 3000, NODE_ENV } = process.env;

// validate if we have all the env variables setup.
validateEnvVar();
Expand Down Expand Up @@ -47,7 +47,5 @@ app.use(errorMiddleware);

// start listening
app.listen(PORT, () => {
console.info(
`[Node][${NODE_ENV}] App v${version} running at: http://localhost:${PORT}`,
);
console.info(`[Node][${NODE_ENV}] App v${version} running on PORT ${PORT}`);
});
1 change: 0 additions & 1 deletion public/ads.txt

This file was deleted.

11 changes: 9 additions & 2 deletions src/constants/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
const constants = {};

constants.REQUIRED_ENV_VARIABLES = ['FRONTEND_URL', 'JWT_SECRET'];
constants.OPTIONAL_ENV_VARIABLES = ['MONGODB_URI', 'MONGODB_DB_NAME'];
constants.REQUIRED_ENV_VARIABLES = ['JWT_SECRET'];
constants.OPTIONAL_ENV_VARIABLES = [
'FRONTEND_URL',
'MONGODB_URI',
'MONGODB_DB_NAME',
'GOOGLE_TAG_ID',
'GOOGLE_PUBLISHER_ID',
'GOOGLE_ADS_TXT_CONTENT',
];

constants.requestWhitelist = ['/favicon.ico', '/static', '/image/i/'];

Expand Down
10 changes: 7 additions & 3 deletions src/middleware/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ const errorMiddleware = (err, req, res, next) => {
return;
}

console.log('*-*-* [start] error *-*-*');
console.log(err);
console.log('*-*-* [end] error *-*-*');
if (err.status === 404) {
console.log('*** 404 Error ***', err.message || err);
} else {
console.log('*-*-* [start] error *-*-*');
console.log(err.message || err);
console.log('*-*-* [end] error *-*-*');
}

if (err.message === 'jwt expired') {
return res.status(401).send({ ...err, message: 'Token Expired!' });
Expand Down
98 changes: 76 additions & 22 deletions src/middleware/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,17 @@ if (MONGODB_URI) {
require('../db/mongoose');
}

let count = 0;
startCountLogger();

function logger(req, res, next) {
if (isRequestInWhitelist(req)) {
next();
return;
}

count += 1;

// request data
req._startAt = undefined;
req._startTime = undefined;
Expand All @@ -23,39 +33,38 @@ function logger(req, res, next) {
recordStartTime.call(req);

function logRequest() {
// handle log
if (isRequestInWhitelist(req)) return;
const requestURL = req.originalUrl || req.url;
const requestMetaData = {
requestIP: getIP(req),
requestMethod: req.method,
requestTimeISO: new Date().toISOString(),
requestUA: req.headers['user-agent'],
requestURL,
};

const responseMetaData = {
responseCode: getResponseStatus(req, res),
responseTimeMS: getResponseTime(req, res),
};

const referrer = req.headers.referer || req.headers.referrer;

const log = new Log({
requestMetaData: {
requestIP: getIP(req),
requestMethod: req.method,
requestTimeISO: new Date().toISOString(),
requestUA: req.headers['user-agent'],
requestURL: req.originalUrl || req.url,
},

responseMetaData: {
responseCode: getResponseStatus(req, res),
responseTimeMS: getResponseTime(req, res),
},

referrer: req.headers.referer || req.headers.referrer,
requestMetaData,
responseMetaData,
referrer,
totalTimeMS: getTotalTime(req, res),
});

if (MONGODB_URI) {
log.save((err, result) => {
log.save(err => {
if (err) {
console.log({ logError: err.message });
return;
}

console.log(result);
});
} else {
console.log(log);
}

console.log(`Resource: ${requestURL}; Referrer: ${referrer || '-'}`);
}

// record response start
Expand Down Expand Up @@ -129,3 +138,48 @@ function isHeadersSent(res) {
? Boolean(res._header)
: res.headersSent;
}

function startCountLogger() {
const countTime = new Date().getTime();

setInterval(() => {
const diff = timeDifference(countTime, new Date().getTime());
console.info(`[Count] "${count}" requests in ${diff}`);
}, 30 * 1000 /* 30 Seconds */);
}

// Calculate the time difference between two dates
function timeDifference(startDateMS, endDateMS) {
// Calculate the difference in milliseconds
const difference = endDateMS - startDateMS;

// Calculate the difference in minutes
const minutes = Math.floor(difference / 1000 / 60);

// Calculate the difference in hours
const hours = Math.floor(difference / 1000 / 60 / 60);

// Calculate the difference in days
const days = Math.floor(difference / 1000 / 60 / 60 / 24);

// Calculate the number of remaining hours
const remainingHours = hours % 24;

// Calculate the number of remaining minutes
const remainingMinutes = minutes % 60;

// Build the result string
let result = '';
if (days > 0) {
result += `${days} days, `;
}
if (remainingHours > 0) {
result += `${remainingHours} hours, `;
}
if (remainingMinutes >= 0) {
result += `${remainingMinutes} minutes`;
}

// Return the result string
return result;
}
27 changes: 24 additions & 3 deletions src/routes/static.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
const router = require('express').Router();
const path = require('path');

const {
GOOGLE_TAG_ID,
GOOGLE_PUBLISHER_ID,
GOOGLE_ADS_TXT_CONTENT,
} = process.env;
const commonVariables = {
googleTagId: GOOGLE_TAG_ID,
googlePublisherId: GOOGLE_PUBLISHER_ID,
};

const availableResources = [
'products',
'carts',
Expand All @@ -14,11 +24,12 @@ const availableResources = [
];

router.get('/', (req, res) => {
res.render('index', { path: 'home' });
res.render('index', { ...commonVariables, path: 'home' });
});

router.get('/docs', (req, res) => {
res.render('docs', {
...commonVariables,
path: 'docs',
page: '',
description: `Different types of REST Endpoints filled with JSON data to use in developing the frontend without worrying about writing a backend.`,
Expand All @@ -34,6 +45,7 @@ router.get('/docs/:resource', (req, res, next) => {
}

res.render(`docs-${resource}`, {
...commonVariables,
path: 'docs',
page: resource,
description: `REST Endpoints filled with ${resource.toUpperCase()} JSON data to use in developing the frontend without worrying about writing a backend.`,
Expand All @@ -48,8 +60,17 @@ router.get('/sitemap.xml', (req, res) => {
res.sendFile(path.join(__dirname, '../../', 'public', 'sitemap.xml'));
});

router.get('/ads.txt', (req, res) => {
res.sendFile(path.join(__dirname, '../../', 'public', 'ads.txt'));
router.get('/ads.txt', (req, res, next) => {
if (GOOGLE_ADS_TXT_CONTENT) {
res.attachment('ads.txt');
res.set('Content-Disposition', 'inline');
res.type('txt');
res.send(GOOGLE_ADS_TXT_CONTENT);

return;
}

next();
});

module.exports = router;
14 changes: 8 additions & 6 deletions views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@
<script defer src="/static/js/common.js"></script>
<script defer src="/static/js/main.js"></script>

<% if (typeof(googleTagId) !== "undefined") { %>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script
async
src="https://www.googletagmanager.com/gtag/js?id=G-31N299BXMJ"
src="https://www.googletagmanager.com/gtag/js?id=<%= googleTagId %>"
></script>
<script>
window.dataLayer = window.dataLayer || [];
Expand All @@ -41,8 +42,9 @@
}
gtag('js', new Date());
gtag('config', 'G-31N299BXMJ');
gtag('config', '<%= googleTagId %>');
</script>
<% } %>

<title>
DummyJSON - Fake REST API of JSON data for development
Expand Down Expand Up @@ -155,10 +157,10 @@
<div class="why-us">
<h2>Got tired of Lorem ipsum data?</h2>
<p>
With DummyJSON, what you get is different types of REST Endpoints
filled with JSON data which you can use in developing the frontend
with your favorite framework and library without worrying about
writing a backend.
With FakeProductsAPI, what you get is different types of REST
Endpoints filled with JSON data which you can use in developing the
frontend with your favorite framework and library without worrying
about writing a backend.
</p>
</div>

Expand Down
6 changes: 4 additions & 2 deletions views/partials/ads.ejs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
<% if (typeof(googlePublisherId) !== "undefined") { %>
<script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1874186634672982"
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=<%= googlePublisherId %>"
crossorigin="anonymous"
></script>
<ins
class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-1874186634672982"
data-ad-client="<%= googlePublisherId %>"
data-ad-slot="<%= adId %>"
data-ad-format="auto"
data-full-width-responsive="true"
Expand All @@ -16,3 +17,4 @@
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<% } %>
10 changes: 7 additions & 3 deletions views/partials/docs-head.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@
<link href="/static/css/docs.css" rel="stylesheet" />

<script src="/static/highlight.js/highlight.min.js"></script>
<% if (typeof(googleTagId) !== "undefined") { %>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script
async
src="https://www.googletagmanager.com/gtag/js?id=G-31N299BXMJ"
src="https://www.googletagmanager.com/gtag/js?id=<%= googleTagId %>"
></script>
<script>
window.dataLayer = window.dataLayer || [];
Expand All @@ -40,13 +42,15 @@
}
gtag('js', new Date());
gtag('config', 'G-31N299BXMJ');
gtag('config', '<%= googleTagId %>');
</script>
<% } %>

<script defer src="/static/js/docs.js"></script>
<script defer src="/static/js/common.js"></script>

<title>
<%= page ? page.toUpperCase() + ` - Dummy REST API of JSON data for development` : 'Docs - Fake REST API of JSON data | DummyJSON' %>
<%= page ? page.toUpperCase() + ` - Dummy REST API of JSON data for
development` : 'Docs - Fake REST API of JSON data | FakeProductsAPI' %>
</title>
</head>

0 comments on commit 3937ccb

Please sign in to comment.