I cant figure out how to rewrite my handler functions in typescript: import {…
- User
I cant figure out how to rewrite my handler functions in typescript:
import { NextFunction, Request, Response, RequestHandler } from "express";
interface ResponseData { errors?: string[] | Record<string, any>; [key: string]: any; }
interface unhandledResponse extends Response { sendResponse(data: ResponseData | null): void; }
export const responseHandler: RequestHandler = (req: Request, res: unhandledResponse, next: NextFunction) => { res.sendResponse = function (data: ResponseData | null) { // 404 - Not Found (null/undefined) if (!data) { console.error(
Not found in ${req.method} ${req.path}); return res.status(404).json({ error: "Not found" }); }code// 400 - Bad Request (validation errors) if (data.errors) { console.error( `Validation error in ${req.method} ${req.path}:`, data.errors ); return res.status(400).json({ error: data.errors }); } // 201 - Created (POST success) if (req.method === "POST") { console.log(`Resource created in ${req.method} ${req.path}`); return res.status(201).json(data); } // 200 - OK (default success) return res.json(data);}; next(); };
interface CustomError extends Error { status?: number; }
export const errorHandler = (err: CustomError, req: Request, res: Response, next: NextFunction) => { console.error(
Something went wrong!); console.error(Failed in ${req.method} ${req.path}:, err.message);// 500 - Internal Server Error (default error case) // Use error's status if it exists, otherwise 500 res.status(err.status || 500).json({ error: err.message }); };
//
import express from "express"; import "express-async-errors"; import cors from "cors"; import mongoose from "mongoose"; import applicationRouter from "./routes/applications.js"; import resumeRouter from "./routes/resumes.js"; import { responseHandler, errorHandler } from "./resUtil.js"; import dotenv from "dotenv";
dotenv.config();
const mongo_uri = process.env.MONGO_URI; if(!mongo_uri) throw new Error("Mongo_uri undefined"); await mongoose.connect(mongo_uri);
const app = express(); app.use(express.json()); app.use(cors()); app.use(responseHandler);
app.use("/applications", applicationRouter); app.use("/resumes", resumeRouter);
app.use(errorHandler);
app.listen(process.env.PORT, () => { console.log(
jobFlow listening on port ${process.env.PORT}); }); - Assistant