Refactor API URLs to use centralized buildApiUrl utility and environment variables

This commit is contained in:
Ravindranbit 2026-04-28 16:31:48 +05:30
parent 947f8114d2
commit 9f25fe3228
7 changed files with 30 additions and 12 deletions

1
.env.example Normal file
View File

@ -0,0 +1 @@
NEXT_PUBLIC_API_BASE_URL=http://localhost:3000/api/

View File

@ -4,6 +4,7 @@ import IconTrashLines from '../icon/icon-trash-lines';
import axios from 'axios'; import axios from 'axios';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { showMessage } from '@/utils/CommonFunction.utils'; import { showMessage } from '@/utils/CommonFunction.utils';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface FormValues { interface FormValues {
year: string; year: string;
@ -85,7 +86,7 @@ const CreateEventForm: React.FC = () => {
} }
try { try {
const ImageUpload = await axios.post(`https://api.tamilculturewaterloo.org/api/upload/single`, data, { const ImageUpload = await axios.post(buildApiUrl('upload/single'), data, {
headers: { headers: {
"Content-Type": "multipart/form-data", // important for file upload "Content-Type": "multipart/form-data", // important for file upload
}, },
@ -99,7 +100,7 @@ const CreateEventForm: React.FC = () => {
eventimageurl: ImageUpload?.data?.data?.fullUrl eventimageurl: ImageUpload?.data?.data?.fullUrl
} }
const res = await axios.post(`https://api.tamilculturewaterloo.org/api/events`, createData) const res = await axios.post(buildApiUrl('events'), createData)
console.log("res", res) console.log("res", res)
showMessage("Event Created Successfully", "success") showMessage("Event Created Successfully", "success")
router?.push(`/`) router?.push(`/`)

View File

@ -3,6 +3,7 @@ import React, { useState, ChangeEvent, FormEvent } from 'react';
import IconTrashLines from '../icon/icon-trash-lines'; import IconTrashLines from '../icon/icon-trash-lines';
import axios from 'axios'; import axios from 'axios';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface FormErrors { interface FormErrors {
[key: string]: string; [key: string]: string;
@ -61,7 +62,7 @@ const CreateEventGalleryForm: React.FC<EditEventFormProps> = ({ eventId }) => {
formData.append(`files`, file); formData.append(`files`, file);
}); });
const uploadRes = await axios.post(`https://api.tamilculturewaterloo.org/api/upload/multiple`, formData) const uploadRes = await axios.post(buildApiUrl('upload/multiple'), formData)
console.log("uploadres", uploadRes) console.log("uploadres", uploadRes)
const uploadedUrls = uploadRes?.data?.data?.map((image: any) => image?.fullUrl) || []; const uploadedUrls = uploadRes?.data?.data?.map((image: any) => image?.fullUrl) || [];
@ -75,7 +76,7 @@ const CreateEventGalleryForm: React.FC<EditEventFormProps> = ({ eventId }) => {
// Step 3: Call bulk API // Step 3: Call bulk API
await axios.post( await axios.post(
`https://api.tamilculturewaterloo.org/api/event-images/bulk`, buildApiUrl('event-images/bulk'),
body body
); );

View File

@ -3,6 +3,7 @@ import React, { useState, useEffect, ChangeEvent, FormEvent } from 'react';
import IconTrashLines from '../icon/icon-trash-lines'; import IconTrashLines from '../icon/icon-trash-lines';
import axios from 'axios'; import axios from 'axios';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface FormValues { interface FormValues {
year: string; year: string;
@ -43,7 +44,7 @@ const EditEventForm: React.FC<EditEventFormProps> = ({ eventId }) => {
const getEvent = async () => { const getEvent = async () => {
try { try {
const res = await axios.get(`https://api.tamilculturewaterloo.org/api/events/${eventId}`); const res = await axios.get(buildApiUrl(`events/${eventId}`));
const data = res?.data?.data; const data = res?.data?.data;
setFormData({ setFormData({
@ -124,7 +125,7 @@ const EditEventForm: React.FC<EditEventFormProps> = ({ eventId }) => {
imgFormData.append('file', formData.eventimageurl); imgFormData.append('file', formData.eventimageurl);
const uploadRes = await axios.post( const uploadRes = await axios.post(
'https://api.tamilculturewaterloo.org/api/upload/single', buildApiUrl('upload/single'),
imgFormData, imgFormData,
{ headers: { 'Content-Type': 'multipart/form-data' } } { headers: { 'Content-Type': 'multipart/form-data' } }
); );
@ -140,7 +141,7 @@ const EditEventForm: React.FC<EditEventFormProps> = ({ eventId }) => {
eventimageurl: imageUrl, eventimageurl: imageUrl,
}; };
const res = await axios.put(`https://api.tamilculturewaterloo.org/api/events/${eventId}`, updatedData, ); const res = await axios.put(buildApiUrl(`events/${eventId}`), updatedData, );
console.log('Event updated:', res.data); console.log('Event updated:', res.data);
router.push('/'); router.push('/');

View File

@ -9,6 +9,7 @@ import axios from 'axios';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import IconTrashLines from '../icon/icon-trash-lines'; import IconTrashLines from '../icon/icon-trash-lines';
import Swal from 'sweetalert2'; import Swal from 'sweetalert2';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface EditEventFormProps { interface EditEventFormProps {
eventId: string | null; eventId: string | null;
@ -29,7 +30,7 @@ const ListOfEventsGallery: React.FC<EditEventFormProps> = ({ eventId }) => {
const getEventGallery = async () => { const getEventGallery = async () => {
try { try {
const res = await axios.get(`https://api.tamilculturewaterloo.org/api/event-images/event/${eventId}`); const res = await axios.get(buildApiUrl(`event-images/event/${eventId}`));
const formatted = res.data?.data?.map((img: any) => ({ const formatted = res.data?.data?.map((img: any) => ({
id: img.id, // ensure ID is preserved for deletion id: img.id, // ensure ID is preserved for deletion
src: img.imageurl, src: img.imageurl,
@ -58,7 +59,7 @@ const ListOfEventsGallery: React.FC<EditEventFormProps> = ({ eventId }) => {
}).then(async (result) => { }).then(async (result) => {
if (result.isConfirmed) { if (result.isConfirmed) {
try { try {
await axios.delete(`https://api.tamilculturewaterloo.org/api/event-images/${item.id}`); await axios.delete(buildApiUrl(`event-images/${item.id}`));
Swal.fire({ Swal.fire({
title: 'Deleted!', title: 'Deleted!',
text: 'Your file has been deleted.', text: 'Your file has been deleted.',

View File

@ -7,6 +7,7 @@ import IconTrashLines from '../icon/icon-trash-lines';
import IconPencil from '../icon/icon-pencil'; import IconPencil from '../icon/icon-pencil';
import Swal from 'sweetalert2'; import Swal from 'sweetalert2';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Knowledge Base', title: 'Knowledge Base',
@ -23,7 +24,7 @@ const ListOfEvents = () => {
const getEvents = async () => { const getEvents = async () => {
try { try {
const eventRes: any = await axios?.get(`https://api.tamilculturewaterloo.org/api/events`) const eventRes: any = await axios?.get(buildApiUrl('events'))
console.log("eventRes", eventRes) console.log("eventRes", eventRes)
setEvents(eventRes?.data?.data) setEvents(eventRes?.data?.data)
} catch (error) { } catch (error) {
@ -61,7 +62,7 @@ const ListOfEvents = () => {
}).then(async (result) => { }).then(async (result) => {
if (result.isConfirmed) { if (result.isConfirmed) {
try { try {
await axios.delete(`https://api.tamilculturewaterloo.org/api/events/${event.id}`); await axios.delete(buildApiUrl(`events/${event.id}`));
Swal.fire({ Swal.fire({
title: 'Deleted!', title: 'Deleted!',
text: 'Your file has been deleted.', text: 'Your file has been deleted.',

View File

@ -1 +1,13 @@
export const Baseurl = "https://api.tamilculturewaterloo.org/api/" const DEFAULT_BASE_URL = 'https://api.tamilculturewaterloo.org/api/';
const configuredBaseUrl =
typeof process !== 'undefined' && process.env.NEXT_PUBLIC_API_BASE_URL
? process.env.NEXT_PUBLIC_API_BASE_URL
: DEFAULT_BASE_URL;
export const Baseurl = configuredBaseUrl.endsWith('/') ? configuredBaseUrl : `${configuredBaseUrl}/`;
export const buildApiUrl = (path) => {
const normalizedPath = String(path).replace(/^\/+/, '');
return `${Baseurl}${normalizedPath}`;
};