Skip to content

Commit

Permalink
feat: simplify cron env variable use
Browse files Browse the repository at this point in the history
  • Loading branch information
henb13 committed Nov 1, 2023
1 parent 0593248 commit 6313a1a
Show file tree
Hide file tree
Showing 6 changed files with 19 additions and 53 deletions.
2 changes: 1 addition & 1 deletion client/src/hooks/useFetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const useFetch = (url) => {
.then((res) => {
if (!res.ok) {
throw Error(
res.status == 429
res.status === 429
? "You are making too many requests, please try again later."
: "Something went wrong, please try again later."
);
Expand Down
4 changes: 1 addition & 3 deletions server/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ SUPABASE_API_KEY_DEV=YOUR_SUPABASE_DEV_API_KEY

PORT=3000

# How often to compare with Spotify API in minutes
CRON_INTERVAL=30

CRON_INTERVAL_EVERY_X_HOURS=2

USE_MOCK_DATA=true

Expand Down
14 changes: 3 additions & 11 deletions server/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ const NodeCache = require("node-cache");
router.use(express.json());
require("dotenv").config();

const CRON_INTERVAL = parseInt(process.env.CRON_INTERVAL, 10) ?? 30;

const cache = new NodeCache({ stdTTL: CRON_INTERVAL * 60 });
const cache = new NodeCache({ stdTTL: 3600 });

const KEYS = {
missingEpisodes: "missing-episodes",
Expand All @@ -26,22 +24,16 @@ const allowOrigin =
router.get("/api/episodes", async (_, res) => {
console.info("request fired");

const maxAgeMs = Math.min(
cache.getTtl(KEYS.missingEpisodes),
cache.getTtl(KEYS.shortenedEpisodes)
);
const maxAge = maxAgeMs ? Math.round((new Date(maxAgeMs).getTime() - Date.now()) / 1000) : 0;

res.header({
"cache-control": `no-transform, max-age=${maxAge}`,
"cache-control": `no-transform, max-age=1800`,
"Access-Control-Allow-Origin": allowOrigin,
});

const missingCacheExists = cache.has(KEYS.missingEpisodes);
const shortenedCacheExists = cache.has(KEYS.shortenedEpisodes);
const lastCheckedExists = cache.has(KEYS.lastChecked);

if (!missingCacheExists || !shortenedCacheExists || !lastCheckedExists) {
if ([missingCacheExists, shortenedCacheExists, lastCheckedExists].some((c) => !c)) {
const client = await pool.connect();
const db = DB(client);

Expand Down
14 changes: 7 additions & 7 deletions server/lib/getSpotifyEpisodes.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
const initializeSpotifyClient = require("./spotify-client");
const { spotifyClient } = require("./spotify-client");

const JRE_SHOW_ID = "4rOoJ6Egrf8K2IrywzwOMk";

let spotifyClient;

async function getSpotifyEpisodes() {
if (!spotifyClient) {
spotifyClient = await initializeSpotifyClient();
}

try {
const data = await spotifyClient.clientCredentialsGrant();
const accessToken = data.body["access_token"];
spotifyClient.setAccessToken(accessToken);

const spotifyEpisodes = [];
const episodes = await spotifyClient.getShowEpisodes(JRE_SHOW_ID, {
market: "US",
Expand All @@ -33,12 +31,14 @@ async function getSpotifyEpisodes() {
limit: 50,
offset: spotifyEpisodes.length,
});

spotifyEpisodes.push(
...episodes.body.items.map((ep) => {
return { name: ep.name, duration: ep.duration_ms };
})
);
}

console.log(
`${spotifyEpisodes.length} out of ${totalEpisodes} JRE episodes on Spotify successfully fetched`
);
Expand Down
34 changes: 5 additions & 29 deletions server/lib/spotify-client.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,9 @@
const SpotifyWebApi = require("spotify-web-api-node");
require("dotenv").config();

async function initializeSpotifyClient() {
try {
const spotifyClient = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
});
const spotifyClient = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
});

const data = await spotifyClient.clientCredentialsGrant();
const accessToken = data.body["access_token"];
const refreshToken = data.body["refresh_token"];
const expiresIn = data.body["expires_in"];

spotifyClient.setAccessToken(accessToken);
spotifyClient.setRefreshToken(refreshToken);

setInterval(async () => {
const data = await spotifyClient.refreshAccessToken();
const accessToken = data.body["access_token"];
spotifyClient.setAccessToken(accessToken);

console.log("The access token has been refreshed!");
}, expiresIn - 60 * 1000);

spotifyClient.setAccessToken(data.body["access_token"]);
} catch (error) {
return null;
}
}

module.exports = { initializeSpotifyClient };
module.exports = { spotifyClient };
4 changes: 2 additions & 2 deletions server/worker/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ const schedule = require("node-schedule");
const refreshDb = require("./tasks/refreshDb");
require("dotenv").config();
// eslint-disable-next-line no-undef
const { CRON_INTERVAL } = process.env;
const { CRON_INTERVAL_EVERY_X_HOURS } = process.env;

schedule.scheduleJob(`*/${CRON_INTERVAL} * * * *`, refreshDb);
schedule.scheduleJob(`2 */${CRON_INTERVAL_EVERY_X_HOURS} * * *`, refreshDb);

0 comments on commit 6313a1a

Please sign in to comment.