Skip to content

Commit

Permalink
Merge pull request #21 from avantifellows/feature/data-fetching-using…
Browse files Browse the repository at this point in the history
…-fetch

Replacing axios with fetch for Nextjs Caching and Revalidation
  • Loading branch information
Bahugunajii authored Jan 16, 2024
2 parents 43f2388 + 7d52b2f commit 4d9b360
Show file tree
Hide file tree
Showing 9 changed files with 221 additions and 134 deletions.
158 changes: 101 additions & 57 deletions api/afdb/library.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
"use server"

import axios from 'axios';
import { Curriculum, Subject, Grade, Chapter, Resource, Topic } from '../../app/types'
import getAxiosConfig from '../axiosConfig';
import getFetchConfig from '../fetchConfig';

const url = process.env.AF_DB_SERVICE_URL;
const baseUrl = process.env.AF_DB_SERVICE_URL;
const bearerToken = process.env.AF_DB_SERVICE_BEARER_TOKEN || '';

export const getCurriculum = async (curriculumName: string): Promise<Curriculum[]> => {
try {
const response = await axios.get(`${url}/curriculum`, {
params: { name: curriculumName },
...getAxiosConfig(bearerToken),
});
return response.data;
const url = `${baseUrl}/curriculum?name=${encodeURIComponent(curriculumName)}`;
const response = await fetch(url, getFetchConfig(bearerToken),);

if (!response.ok) {
throw new Error(`Error in fetching curriculumId for ${curriculumName}: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error(`Error in fetching curriculumId for ${curriculumName}:`, error);
throw error;
Expand All @@ -22,53 +25,84 @@ export const getCurriculum = async (curriculumName: string): Promise<Curriculum[

export const getSubjects = async (subjectName: string): Promise<Subject[]> => {
try {
const response = await axios.get(`${url}/subject`, {
params: { name: subjectName },
...getAxiosConfig(bearerToken),
});
return response.data;
const url = `${baseUrl}/subject?name=${encodeURIComponent(subjectName)}`;
const response = await fetch(url, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching subjects for ${subjectName}: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetching Subjects:", error);
console.error(`Error in fetching subjects for ${subjectName}:`, error);
throw error;
}
};

export const getGrades = async (number: number): Promise<Grade[]> => {
try {
const response = await axios.get(`${url}/grade`, {
params: { number: number },
...getAxiosConfig(bearerToken),
});
return response.data;
const url = `${baseUrl}/grade?number=${number}`;
const response = await fetch(url, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching grades for ${number}: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetching Grades:", error);
console.error(`Error in fetching grades for ${number}:`, error);
throw error;
}
};

export const getChapters = async (subjectId?: number, gradeId?: number, id?: number, curriculumId?: number): Promise<Chapter[]> => {
export const getChapters = async (
subjectId?: number,
gradeId?: number,
id?: number,
curriculumId?: number
): Promise<Chapter[]> => {
try {
const response = await axios.get(`${url}/chapter`, {
params: { id: id, subject_id: subjectId, grade_id: gradeId, curriculum_id: curriculumId },
...getAxiosConfig(bearerToken),
});
return response.data;
const queryParams = new URLSearchParams();
if (id !== undefined) queryParams.append('id', id.toString());
if (subjectId !== undefined) queryParams.append('subject_id', subjectId.toString());
if (gradeId !== undefined) queryParams.append('grade_id', gradeId.toString());
if (curriculumId !== undefined) queryParams.append('curriculum_id', curriculumId.toString());

const urlWithParams = `${baseUrl}/chapter?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching chapters: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetching Chapters:", error);
console.error("Error in fetching chapters:", error);
throw error;
}
};

export const getTopics = async (chapterIds: number[]): Promise<Topic[]> => {
const topicPromises = chapterIds.map(async (chapterId) => {
try {
const response = await axios.get(`${url}/topic`, {
params: { chapter_id: chapterId },
...getAxiosConfig(bearerToken),
const queryParams = new URLSearchParams({
chapter_id: chapterId.toString(),
});
return response.data || [];

const urlWithParams = `${baseUrl}/topic?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching topics for chapterId ${chapterId}: ${response.statusText}`);
}

const data = await response.json();
return data || [];
} catch (error) {
console.error("Error in fetching topics for chapterId", chapterId, ":", error);
console.error(`Error in fetching topics for chapterId ${chapterId}:`, error);
return [];
}
});
Expand All @@ -79,48 +113,58 @@ export const getTopics = async (chapterIds: number[]): Promise<Topic[]> => {

export const getSource = async (sourceId: number) => {
try {
const response = await axios.get(`${url}/source`, {
params: { id: sourceId },
...getAxiosConfig(bearerToken),
const queryParams = new URLSearchParams({
id: sourceId.toString(),
});

if (response.data) {
return response.data;
const urlWithParams = `${baseUrl}/source?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching source for sourceId ${sourceId}: ${response.statusText}`);
}

const data = await response.json();
return data || null;
} catch (error) {
console.error("Error in fetching Source for sourceId", sourceId, ":", error);
console.error(`Error in fetching source for sourceId ${sourceId}:`, error);
return null;
}
return null;
};


export const getResourcesWithSource = async (topicIds: number[]): Promise<Resource[]> => {
const resourcePromises = topicIds.map(async (topicId) => {
try {
const response = await axios.get(`${url}/resource`, {
params: { topic_id: topicId },
...getAxiosConfig(bearerToken),
const queryParams = new URLSearchParams({
topic_id: topicId.toString(),
});

if (response.data) {
const chapterResources: Resource[] = response.data;
const urlWithParams = `${baseUrl}/resource?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching resources for topicId ${topicId}: ${response.statusText}`);
}

const chapterResources: Resource[] = await response.json();

const sourcePromises = chapterResources.map(async (resource) => {
if (resource.source_id) {
const sourceData = await getSource(resource.source_id);
if (sourceData) {
resource.link = sourceData[0].link;
}
const sourcePromises = chapterResources.map(async (resource) => {
if (resource.source_id) {
const sourceData = await getSource(resource.source_id);
if (sourceData) {
resource.link = sourceData[0].link;
}
return resource;
});
}
return resource;
});

const resourcesWithSource = await Promise.all(sourcePromises);
return resourcesWithSource;
}
const resourcesWithSource = await Promise.all(sourcePromises);
return resourcesWithSource;
} catch (error) {
console.error("Error in fetching Topic for topicId", topicId, ":", error);
console.error("Error in fetching resources for topicId", topicId, ":", error);
return [];
}
return [];
});

const resourceResponses = await Promise.all(resourcePromises);
Expand Down
67 changes: 48 additions & 19 deletions api/afdb/session.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,47 @@
"use server"

import axios from 'axios';
import getAxiosConfig from '../axiosConfig';
import getFetchConfig from '../fetchConfig';

const url = process.env.AF_DB_SERVICE_URL;
const bearerToken = process.env.AF_DB_SERVICE_BEARER_TOKEN || '';

export const getGroupUser = async (userDbId: number) => {
try {
const response = await axios.get(`${url}/group-user`, {
params: { user_id: userDbId },
...getAxiosConfig(bearerToken),
const queryParams = new URLSearchParams({
user_id: userDbId.toString(),
});
return response.data;

const urlWithParams = `${url}/group-user?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching Session Details: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetching Session Details:", error);
throw error;
}
};


export const getGroupSessions = async (groupTypeId: number) => {
try {
const response = await axios.get(`${url}/group-session`, {
params: { group_type_id: groupTypeId },
...getAxiosConfig(bearerToken),
const queryParams = new URLSearchParams({
group_type_id: groupTypeId.toString(),
});
return response.data;

const urlWithParams = `${url}/group-session?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching Session Details: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetching Session Details:", error);
throw error;
Expand All @@ -34,10 +50,15 @@ export const getGroupSessions = async (groupTypeId: number) => {

export const getSessions = async (sessionId: number) => {
try {
const response = await axios.get(`${url}/session/${sessionId}`, {
...getAxiosConfig(bearerToken),
});
return response.data;
const urlWithParams = `${url}/session/${sessionId}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching Session Details: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetching Session Details:", error);
throw error;
Expand All @@ -46,13 +67,21 @@ export const getSessions = async (sessionId: number) => {

export const getGroupTypes = async (groupTypeId: number) => {
try {
const response = await axios.get(`${url}/group-type`, {
params: { id: groupTypeId, type: "batch" },
...getAxiosConfig(bearerToken),
const queryParams = new URLSearchParams({
id: groupTypeId.toString(),
type: "batch"
});
return response.data;
const urlWithParams = `${url}/group-type?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error in fetching Group Type Details: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetching Group Types:", error);
console.error("Error in fetching Group Type Details:", error);
throw error;
}
};
27 changes: 17 additions & 10 deletions api/afdb/userName.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
"use server"
"use server";

import axios from 'axios';
import getAxiosConfig from '../axiosConfig';
import { User } from '@/app/types';
import getFetchConfig from '../fetchConfig';
import { Student, User } from '@/app/types';

export const getUserName = async (studentId: string): Promise<User | null> => {
const url = process.env.AF_DB_SERVICE_URL;
const bearerToken = process.env.AF_DB_SERVICE_BEARER_TOKEN!;

try {
const response = await axios.get(`${url}/student`, {
params: { student_id: studentId },
...getAxiosConfig(bearerToken),
const queryParams = new URLSearchParams({
student_id: studentId,
});

if (response.data.length === 0) {
const urlWithParams = `${url}/student?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

if (!response.ok) {
throw new Error(`Error fetching student data: ${response.statusText}`);
}

const data: Student[] = await response.json();

if (data.length === 0) {
console.warn(`No user found for student ID: ${studentId}`);
return null;
}

return response.data[0].user;
return data[0].user;
} catch (error) {
console.error('Error fetching student data:', error);
throw error;
}
}
};
20 changes: 0 additions & 20 deletions api/axiosConfig.ts

This file was deleted.

Loading

0 comments on commit 4d9b360

Please sign in to comment.