From 550ede2ee0a7dbc5196e6b85a30a73fa1c5eee11 Mon Sep 17 00:00:00 2001 From: yznahmad Date: Sat, 21 Jun 2025 02:32:58 +0300 Subject: [PATCH] Add scheduleregdww5sudfw side ddd n --- docker-compose.yml | 7 ++- webapp/src/app/api/health/route.ts | 23 +++++++ .../src/app/api/user/actions/workers/route.ts | 40 ++++++++++-- webapp/src/database/dbConnect.ts | 62 ++++++++++++++----- 4 files changed, 111 insertions(+), 21 deletions(-) create mode 100644 webapp/src/app/api/health/route.ts diff --git a/docker-compose.yml b/docker-compose.yml index 44e4e75..a107317 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -36,9 +36,14 @@ services: - NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL} env_file: .env ports: - - "3000" # Let Docker assign a dynamic host port + - "3000:3000" # Map to a fixed port instead of dynamic networks: - infinity-network + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3000/api/health"] + interval: 20s + timeout: 10s + retries: 3 # Worker Service worker: diff --git a/webapp/src/app/api/health/route.ts b/webapp/src/app/api/health/route.ts new file mode 100644 index 0000000..7027ebc --- /dev/null +++ b/webapp/src/app/api/health/route.ts @@ -0,0 +1,23 @@ +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 b2aed8f..57e4c76 100644 --- a/webapp/src/app/api/user/actions/workers/route.ts +++ b/webapp/src/app/api/user/actions/workers/route.ts @@ -7,9 +7,24 @@ export async function POST(req:Request) { try{ // connect to the db - dbConnect(); + await 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, @@ -19,6 +34,7 @@ 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, @@ -30,7 +46,9 @@ 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, @@ -42,9 +60,23 @@ export async function POST(req:Request) "content-type": "application/json" } }) - }catch(e) - { - console.log("e" , e) + } 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 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 4702512..6399551 100644 --- a/webapp/src/database/dbConnect.ts +++ b/webapp/src/database/dbConnect.ts @@ -1,24 +1,54 @@ -//** -//** @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 connection : any = {}; +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 }; +} async function dbConnect() { - if (connection.isConnected) { - return; - } - const db = await mongoose.connect(process.env.DB_URI?? '', { - // @ts-ignore - useNewUrlParser: true, - useUnifiedTopology: true, + 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; }); - console.log('db connected successfully') - connection.isConnected = db.connections[0].readyState; + } + + try { + cached.conn = await cached.promise; + } catch (e) { + cached.promise = null; + throw e; + } + + return cached.conn; } export default dbConnect; \ No newline at end of file