Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(be): cache golemio requests #38

Merged
merged 1 commit into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion apps/backend/src/constants/golemio.const.ts

This file was deleted.

3 changes: 2 additions & 1 deletion apps/backend/src/modules/departure/departure.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { Module } from "@nestjs/common";

import { DepartureController } from "src/modules/departure/departure.controller";
import { DepartureService } from "src/modules/departure/departure.service";
import { GolemioService } from "src/modules/golemio/golemio.service";

@Module({
controllers: [DepartureController],
providers: [DepartureService],
providers: [DepartureService, GolemioService],
imports: [],
})
export class DepartureModule {}
18 changes: 7 additions & 11 deletions apps/backend/src/modules/departure/departure.service.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { Injectable } from "@nestjs/common";
import { unique } from "radash";

import { GOLEMIO_API } from "src/constants/golemio.const";
import { departureBoardsSchema } from "src/modules/departure/schema/departure-boards.schema";
import type { DepartureSchema } from "src/modules/departure/schema/departure.schema";
import { GolemioService } from "src/modules/golemio/golemio.service";
import { PrismaService } from "src/modules/prisma/prisma.service";
import { getDelayInSeconds } from "src/utils/delay";

@Injectable()
export class DepartureService {
constructor(private prisma: PrismaService) {}
constructor(
private prisma: PrismaService,
private golemioService: GolemioService,
) {}

async getDepartures(args: {
stopIds: string[];
Expand Down Expand Up @@ -57,17 +60,10 @@ export class DepartureService {
]),
);

const url = new URL(
`${GOLEMIO_API}/v2/pid/departureboards?minutesAfter=600&${searchParams.toString()}`,
const res = await this.golemioService.getGolemioData(
`/v2/pid/departureboards?minutesAfter=600&${searchParams.toString()}`,
);

const res = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
"X-Access-Token": process.env.GOLEMIO_API_KEY ?? "",
},
});
if (!res.ok) {
throw new Error(
`Failed to fetch departure data: ${res.status} ${res.statusText}`,
Expand Down
36 changes: 36 additions & 0 deletions apps/backend/src/modules/golemio/golemio.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { CACHE_MANAGER } from "@nestjs/cache-manager";
import { Inject, Injectable } from "@nestjs/common";
import { Cache } from "cache-manager";

const TTL = 4 * 1_000;
const GOLEMIO_API = "https://api.golemio.cz";
krystxf marked this conversation as resolved.
Show resolved Hide resolved

@Injectable()
export class GolemioService {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}

async getGolemioData(path: string): Promise<Response> {
const url = `${GOLEMIO_API}${path}`;

const cached = await this.cacheManager.get(url);

if (cached) {
return new Response(JSON.stringify(cached));
}

const res = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
"X-Access-Token": process.env.GOLEMIO_API_KEY ?? "",
},
});
Comment on lines +21 to +27
Copy link

@coderabbitai coderabbitai bot Nov 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Implement retry mechanism for failed requests.

Network requests to external APIs should implement a retry mechanism to handle temporary failures.

Consider implementing a retry mechanism:

import { retry } from '@nestjs/common';

@retry(3, { delay: 1000 }) // Retry 3 times with 1s delay
async fetchWithRetry(url: string, options: RequestInit): Promise<Response> {
    return fetch(url, options);
}

Then use this method in getGolemioData instead of direct fetch.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is neccessary

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@krystxf, understood.

🐰😔


if (res.ok) {
const parsed = await res.clone().json();
await this.cacheManager.set(url, parsed, TTL);
}

return res;
}
krystxf marked this conversation as resolved.
Show resolved Hide resolved
}
Loading