Skip to content

Commit

Permalink
Create a repeating task for fetching stops and address data (#36)
Browse files Browse the repository at this point in the history
Currently, this data is only fetched on bot startup, which is ok with process managers such as PM2, however some hosting platforms make using PM2 redundant, therefore there needs to be a better way to fetch the data without relying on a process restart.
  • Loading branch information
PopFlamingo authored Jul 16, 2022
1 parent 6872169 commit 253b773
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 11 deletions.
52 changes: 45 additions & 7 deletions CTSService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,12 @@ export class CTSService {
timeout: 8000,
});

let queryResults = await CTSService.loadStopCodesMap(ctsAPI);

return new CTSService(ctsAPI, queryResults);
}

static async loadStopCodesMap(ctsAPI: AxiosInstance): Promise<Map<string, StationQueryResult>> {
let geoGouvAPI = axios.create({
baseURL: "https://api-adresse.data.gouv.fr",
timeout: 8000,
Expand Down Expand Up @@ -351,6 +357,8 @@ export class CTSService {
"./resources/last-query-results.json",
savedResults
);
process.env.LAST_STOP_UPDATE = CTSService.formatDateFR(saveData.date)

} catch (e) {
if (e instanceof Error && e.message === "LOAD_FROM_CACHE") {
console.log("Loading from cache");
Expand All @@ -366,16 +374,40 @@ export class CTSService {
);
if (savedResults !== undefined) {
queryResults = savedResults.map;
process.env.LAST_STOP_UPDATE =
savedResults.date.toLocaleDateString("fr-FR");
// Same as above but this time store full date + time using the argument of the function
process.env.LAST_STOP_UPDATE = CTSService.formatDateFR(savedResults.date)

} else {
throw new Error(`Couldn't recover from error`);
}
}

return new CTSService(ctsAPI, queryResults);
return queryResults
}

/**
* Format a date in the "dd/mm/yyyy à hh:mm (heure de Paris)" format
* @param date Date to format
*/
static formatDateFR(date: Date): string {
const dateString = date.toLocaleDateString("fr-FR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
timeZone: "Europe/Paris"
});

const timeString = date.toLocaleTimeString("fr-FR", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "Europe/Paris"
});

return `${dateString} à ${timeString} (heure de Paris)`;
}


static async getAddressDescription(
axiosInstance: AxiosInstance,
location: SIRILocation
Expand Down Expand Up @@ -429,6 +461,12 @@ export class CTSService {
// normalized stop names
private stopCodes: Map<string, StationQueryResult> = new Map();


// Async function updateStopCodes()
async updateStopCodes() {
this.stopCodes = await CTSService.loadStopCodesMap(this.api);
}

async getFormattedSchedule(
userReadableName: string,
stopCodes: string[],
Expand Down Expand Up @@ -540,7 +578,7 @@ export class CTSService {
try {
let schedule = await this.getVisitsForStopCode([stopCode]);
result.push([stopCode, schedule]);
} catch (e) {}
} catch (e) { }
}
return result;
}
Expand Down Expand Up @@ -603,11 +641,11 @@ export class CTSService {
resultVisits.findIndex((resultSchedule) => {
return (
resultSchedule.name ===
elementToMergeVisit.name &&
elementToMergeVisit.name &&
resultSchedule.transportType ===
elementToMergeVisit.transportType &&
elementToMergeVisit.transportType &&
resultSchedule.destinationName ===
elementToMergeVisit.destinationName &&
elementToMergeVisit.destinationName &&
resultSchedule.via === elementToMergeVisit.via
);
}) != -1
Expand Down
13 changes: 9 additions & 4 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ require("dotenv").config();

(async () => {
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

// Set environement variable LAST_STOP_UPDATE to dd/mm/yyyy
process.env.LAST_STOP_UPDATE = new Date().toLocaleDateString("fr-FR");

// Store token in a variable from the DISCORD_TOKEN environment variable
const token = process.env.DISCORD_TOKEN;

Expand Down Expand Up @@ -67,6 +63,15 @@ require("dotenv").config();
await StatsService.load("./stats/", statsSlotCount, excludedIDs)
);

// Update every 6 hours
setInterval(async () => {
try {
await botServices.cts.updateStopCodes()
} catch (e) {
console.error("Couldn't update stop codes", e)
}
}, 1000 * 60 * 60 * 6);

// Create a collection associating command (and subcommand) names with their executors
const commands = new Collection<string, CommandDescriptor>();

Expand Down

0 comments on commit 253b773

Please sign in to comment.