Skip to content

Commit

Permalink
Merge pull request #639 from OneCommunityGlobal/Roberto_Change_OpenCa…
Browse files Browse the repository at this point in the history
…ge_API_Call_To_Backend

Roberto -adds opencage http request to backend timezone route
  • Loading branch information
one-community authored Feb 24, 2024
2 parents b6fadc0 + 67334ed commit 07853e3
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 17 deletions.
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

90 changes: 82 additions & 8 deletions src/controllers/timeZoneAPIController.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,96 @@
// eslint-disable-next-line import/no-extraneous-dependencies
const fetch = require('node-fetch');
const ProfileInitialSetupToken = require('../models/profileInitialSetupToken');
const { hasPermission } = require('../utilities/permissions');

const premiumKey = process.env.TIMEZONE_PREMIUM_KEY;
const commonKey = process.env.TIMEZONE_COMMON_KEY;

const performTimeZoneRequest = async (req, res, apiKey) => {
const { location } = req.params;

if (!location) {
res.status(400).send('Missing location');
return;
}

try {
const geocodeAPIEndpoint = 'https://api.opencagedata.com/geocode/v1/json';
const url = `${geocodeAPIEndpoint}?key=${apiKey}&q=${location}&pretty=1&limit=1`;

const response = await fetch(url);
const data = await response.json();

if (data.status.code !== 200) {
const err = new Error(`opencage error- ${data.status.message}`);
err.status = data.status.code;
throw err;
}

if (data.results && data.results.length) {
const timezone = data.results[0].annotations.timezone.name;
const currentLocation = {
userProvided: location,
coords: {
lat: data.results[0].geometry.lat,
lng: data.results[0].geometry.lng,
},
country: data.results[0].components.country || '',
city: data.results[0].components.city || '',
};
res.status(200).send({ timezone, currentLocation });
} else {
res.status(404).send('No results found');
}
} catch (err) {
const errorMessage = err?.data?.status?.message
? `opencage error, ${err?.data?.status?.message}`
: err.message;
const errorCode = err?.status || 500;
res.status(errorCode).send(errorMessage);
}
};

const timeZoneAPIController = function () {
const getTimeZoneAPIKey = async (req, res) => {
const premiumKey = process.env.TIMEZONE_PREMIUM_KEY;
const commonKey = process.env.TIMEZONE_COMMON_KEY;
if (!req.body.requestor.role) {
const getTimeZone = async (req, res) => {
const { requestor } = req.body;

if (!requestor.role) {
res.status(403).send('Unauthorized Request');
return;
}
if (await hasPermission(req.body.requestor, 'getTimeZoneAPIKey')) {
res.status(200).send({ userAPIKey: premiumKey });

const userAPIKey = (await hasPermission(requestor, 'getTimeZoneAPIKey'))
? premiumKey
: commonKey;
if (!userAPIKey) {
res.status(401).send('API Key Missing');
return;
}

await performTimeZoneRequest(req, res, userAPIKey);
};

const getTimeZoneProfileInitialSetup = async (req, res) => {
const { token } = req.body;
if (!token) {
res.status(400).send('Missing token');
return;
}
res.status(200).send({ userAPIKey: commonKey });

const foundToken = await ProfileInitialSetupToken.findOne({ token });
if (!foundToken) {
res.status(403).send('Unauthorized Request');
return;
}

const userAPIKey = commonKey;
await performTimeZoneRequest(req, res, userAPIKey);
};

return {
getTimeZoneAPIKey,
getTimeZone,
getTimeZoneProfileInitialSetup,
};
};

Expand Down
5 changes: 3 additions & 2 deletions src/routes/timeZoneAPIRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ const routes = function () {
const controller = require('../controllers/timeZoneAPIController')();
const timeZoneAPIRouter = express.Router();

timeZoneAPIRouter.route('/timezone')
.get(controller.getTimeZoneAPIKey);
timeZoneAPIRouter.route('/timezone/:location')
.get(controller.getTimeZone)
.post(controller.getTimeZoneProfileInitialSetup);

return timeZoneAPIRouter;
};
Expand Down
2 changes: 1 addition & 1 deletion src/startup/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ module.exports = function (app) {
next();
return;
}
if (req.originalUrl === '/api/ProfileInitialSetup' || req.originalUrl === '/api/validateToken' || req.originalUrl === '/api/getTimeZoneAPIKeyByToken' && req.method === 'POST' || req.originalUrl === '/api/getTotalCountryCount' && req.method === 'GET'
if (((req.originalUrl === '/api/ProfileInitialSetup' || req.originalUrl === '/api/validateToken' || req.originalUrl === '/api/getTimeZoneAPIKeyByToken') && req.method === 'POST') || (req.originalUrl === '/api/getTotalCountryCount' && req.method === 'GET') || (req.originalUrl.includes('/api/timezone') && req.method === 'POST')
) {
next();
return;
Expand Down

0 comments on commit 07853e3

Please sign in to comment.