diff --git a/webapp/src/app/api/health/route.ts b/webapp/src/app/api/health/route.ts deleted file mode 100644 index 7027ebc..0000000 --- a/webapp/src/app/api/health/route.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { NextResponse } from "next/server"; -import dbConnect from "@/database/dbConnect"; - -export async function GET() { - try { - // Try to connect to the database - await dbConnect(); - - // Return a successful response - return NextResponse.json( - { status: "ok", message: "Service is healthy" }, - { status: 200 } - ); - } catch (error) { - console.error("Health check failed:", error); - - // Return an error response - return NextResponse.json( - { status: "error", message: "Service is unhealthy" }, - { status: 500 } - ); - } -} \ No newline at end of file diff --git a/webapp/src/app/api/user/actions/workers/route.ts b/webapp/src/app/api/user/actions/workers/route.ts index b3483ec..b2aed8f 100644 --- a/webapp/src/app/api/user/actions/workers/route.ts +++ b/webapp/src/app/api/user/actions/workers/route.ts @@ -1,31 +1,15 @@ import dbConnect from "@/database/dbConnect"; import { NextResponse } from "next/server"; import workerModel from "@/database/models/workerModel"; -import mongoose from 'mongoose'; // POST METHOD export async function POST(req:Request) { try{ // connect to the db - await dbConnect(); - + dbConnect(); // get the request payload const { payload } = await req.json(); - - // Validate required fields - if (!payload || !payload.firstName || !payload.lastName) { - return NextResponse.json({ - success: false, - message: "missingRequiredFields", - }, { - status: 400, - headers: { - "content-type": "application/json" - } - }); - } - // get data from formData const firstName : string | null = payload.firstName as string | null, lastName : string | null = payload.lastName as string | null, @@ -35,7 +19,6 @@ export async function POST(req:Request) phone : string | null = payload.phone as string | null, email : string | null = payload.email as string | null, address : string | null = payload.address as string | null; - // save the doc const doc = new workerModel({ firstName, @@ -47,9 +30,7 @@ export async function POST(req:Request) email, address }) - await doc.save() - // return the success response with the new added doc return NextResponse.json({ success: true, @@ -61,23 +42,9 @@ export async function POST(req:Request) "content-type": "application/json" } }) - } catch(e) { - console.error("Error in workers POST:", e); - - // Check for specific error types - if (e instanceof mongoose.Error.ValidationError) { - return NextResponse.json({ - success: false, - message: "validationError", - errors: e.errors - }, { - status: 400, - headers: { - "content-type": "application/json" - } - }); - } - + }catch(e) + { + console.log("e" , e) // catch any error and return an error response return NextResponse.json({ success: false, @@ -97,7 +64,7 @@ export async function GET(req:Request) { try{ // connect to the db - await dbConnect(); + dbConnect(); // get the parms const { searchParams } = new URL(req.url) const type = searchParams.get('type') @@ -125,7 +92,7 @@ export async function GET(req:Request) else if(type == 'search') { // get the searchKeyword param - let searchKeyword = searchParams.get('searchKeyword') || ''; + let searchKeyword = searchParams.get('searchKeyword') // get the search results docs let results = await workerModel.find({ $or: [ @@ -145,28 +112,13 @@ export async function GET(req:Request) return NextResponse.json({ success: true, message: "docsGetedSuccessfully", - data: responseData, - }, { + data: responseData ? responseData : [], + } , { status: 200, - headers: { - "content-type": "application/json" - } }) - } else { - // Handle case when type is not provided or is invalid - return NextResponse.json({ - success: false, - message: "invalidRequestType", - }, { - status: 400, - headers: { - "content-type": "application/json" - } - }); } }catch(e) { - console.error("Error in workers GET:", e); // catch any error and return an error response return NextResponse.json({ success: false, @@ -184,40 +136,14 @@ export async function DELETE(req:Request) { try{ // connect to the db - await dbConnect(); + dbConnect(); // get the parms const { searchParams } = new URL(req.url) const page = searchParams.get('page'), _id : string | null = searchParams.get('_id'), range : number[] = [(parseInt(page?page : '0') - 1) * 4 , 4]; - - if (!_id) { - return NextResponse.json({ - success: false, - message: "missingId", - }, { - status: 400, - headers: { - "content-type": "application/json" - } - }); - } - // delete the doc - const deleteResult = await workerModel.findByIdAndRemove(_id); - - if (!deleteResult) { - return NextResponse.json({ - success: false, - message: "workerNotFound", - }, { - status: 404, - headers: { - "content-type": "application/json" - } - }); - } - + await workerModel.findByIdAndRemove(_id) // get the docs by page const docs = await workerModel.find({}).skip(range[0]).limit(range[1]), // get the size of the docs @@ -225,20 +151,14 @@ export async function DELETE(req:Request) // prepare the return data return NextResponse.json({ success: true, - message: "workerDeletedSuccessfully", + message: "docsGetedSuccessfully", data: { docs, docs_count, } - }, { - status: 200, - headers: { - "content-type": "application/json" - } }) }catch(e) { - console.error("Error in workers DELETE:", e); // catch any error and return an error response return NextResponse.json({ success: false, @@ -256,22 +176,9 @@ export async function PUT(req:Request) { try{ // connect to the db - await dbConnect(); + dbConnect(); // get the request payload const { payload } = await req.json(); - - if (!payload || !payload._id) { - return NextResponse.json({ - success: false, - message: "missingRequiredFields", - }, { - status: 400, - headers: { - "content-type": "application/json" - } - }); - } - // get data from formData const firstName : string | null = payload.firstName as string | null, lastName : string | null = payload.lastName as string | null, @@ -282,9 +189,8 @@ export async function PUT(req:Request) email : string | null = payload.email as string | null, address : string | null = payload.address as string | null, _id : string | null = payload._id as string | null; - // update the doc - let updated_doc = await workerModel.findByIdAndUpdate(_id, { + let updated_doc = await workerModel.findByIdAndUpdate(_id , { firstName, lastName, jobType, @@ -293,20 +199,7 @@ export async function PUT(req:Request) phone, email, address - }, { new: true }); - - if (!updated_doc) { - return NextResponse.json({ - success: false, - message: "workerNotFound", - }, { - status: 404, - headers: { - "content-type": "application/json" - } - }); - } - + }, { new: true }) // return the success response return NextResponse.json({ success: true, @@ -320,7 +213,6 @@ export async function PUT(req:Request) }) }catch(e) { - console.error("Error in workers PUT:", e); // catch any error and return an error response return NextResponse.json({ success: false, diff --git a/webapp/src/database/dbConnect.ts b/webapp/src/database/dbConnect.ts index 6399551..4702512 100644 --- a/webapp/src/database/dbConnect.ts +++ b/webapp/src/database/dbConnect.ts @@ -1,54 +1,24 @@ +//** +//** @desc : Connect to mongodb using mongoose liberary +//** source : https://mongoosejs.com/docs/connections.html +//** +//Todo 1 - Dont forget to add your mongodb connection uri as DB_URI in the .env.local + import mongoose from 'mongoose'; -const MONGODB_URI = process.env.DB_URI || ''; - -if (!MONGODB_URI) { - throw new Error( - 'Please define the DB_URI environment variable inside .env' - ); -} - -/** - * Global is used here to maintain a cached connection across hot reloads - * in development. This prevents connections growing exponentially - * during API Route usage. - */ -let cached = global.mongoose; - -if (!cached) { - cached = global.mongoose = { conn: null, promise: null }; -} +const connection : any = {}; async function dbConnect() { - if (cached.conn) { - return cached.conn; - } - - if (!cached.promise) { - const opts = { - bufferCommands: false, - maxPoolSize: 10, // Maintain up to 10 socket connections - serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds - socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity - }; - - cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => { - console.log('Connected to MongoDB'); - return mongoose; - }).catch((error) => { - console.error('Error connecting to MongoDB:', error); - throw error; + if (connection.isConnected) { + return; + } + const db = await mongoose.connect(process.env.DB_URI?? '', { + // @ts-ignore + useNewUrlParser: true, + useUnifiedTopology: true, }); - } - - try { - cached.conn = await cached.promise; - } catch (e) { - cached.promise = null; - throw e; - } - - return cached.conn; + console.log('db connected successfully') + connection.isConnected = db.connections[0].readyState; } export default dbConnect; \ No newline at end of file diff --git a/webapp/src/redux/features/settings-slice.ts b/webapp/src/redux/features/settings-slice.ts index 68fcb23..ccb5523 100644 --- a/webapp/src/redux/features/settings-slice.ts +++ b/webapp/src/redux/features/settings-slice.ts @@ -33,7 +33,6 @@ type SettingsState = { loadedFirstTime: boolean, } -// Defining the initial state with default values const initialState = { value: { authRedirectPage: '/dashboard', @@ -54,7 +53,7 @@ const initialState = { `, - currencySymbol : "$" + currencySymbol : null }, isUpdatingGeneralSettings: false, isLoadingSettings: false, diff --git a/webapp/src/utils/i18nFallback.ts b/webapp/src/utils/i18nFallback.ts deleted file mode 100644 index 2462b53..0000000 --- a/webapp/src/utils/i18nFallback.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Utility function to safely access translations with fallbacks - */ -export function safeTranslation(t: any, key: string, fallback: string = '') { - try { - if (!t || typeof t !== 'function') { - console.warn(`Translation function not available for key "${key}"`); - return fallback; - } - - const translation = t(key); - // If the translation returns the key itself or contains "MISSING", use fallback - if (!translation || translation === key || translation.includes('MISSING')) { - return fallback; - } - return translation; - } catch (error) { - console.warn(`Translation error for key "${key}":`, error); - return fallback; - } - } - - /** - * Utility function to check if the server is responding - * Can be used to detect server issues early - */ - export async function checkServerConnection() { - try { - const response = await fetch('/api/health', { - method: 'GET', - headers: { - 'Cache-Control': 'no-cache', - }, - }); - - return { - isConnected: response.ok, - status: response.status, - statusText: response.statusText, - }; - } catch (error) { - console.error('Server connection check failed:', error); - return { - isConnected: false, - error: error instanceof Error ? error.message : String(error), - }; - } - } \ No newline at end of file