You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The below code explains how you can write save and write API as per your requirements:
index.js
/** * @author: Bhargab Nath <[email protected]> * */importexpress,{Request,Response}from"express";importmongoosefrom'mongoose';importSearchModelfrom'./Search.model.ts';interfaceSearch{userId: string;name: string;queries: string[];}constapp=express();app.use(express.json());mongoose.connect('mongodb://localhost:27017/my_test_db',{useNewUrlParser: true,useUnifiedTopology: true}).then(()=>console.log('Connected to MongoDB')).catch(error=>console.error('Error connecting to MongoDB:',error));constsearches: Search[]=[];/** * This endpoint accepts POST requests with a JSON body containing a search object, * and saves it to an array in memory * */app.post("/api/searches",async(req: Request,res: Response)=>{constsearch=req.bodyasSearch;try{awaitSearchModel.create(search);res.sendStatus(200).json({message: "Saved data successfully!!!"});}catch(error){console.error('Error saving search:',error);res.sendStatus(500).json({message: "Internal Server Error!"});}});/** * This endpoint accepts GET requests with a userId query parameter, * and returns a JSON array containing the names of all saved searches for that user. * */app.get("/api/searches",async(req: Request,res: Response)=>{const{ userId }=req.query;try{constuserSearches=awaitSearchModel.find({ userId }).select('name').exec();constsearchNames=userSearches.map(search=>search.name);returnres.sendStatus(200).json(searchNames);}catch(error){console.error('Error loading searches:',error);returnres.sendStatus(500).json({message: "Internal Server Error!"});}});/** * endpoint accepts GET requests with a userId query parameter and an id parameter corresponding to the name of a saved search, * and returns the full search object if it exists for that user, or a 404 error if it does not. * */app.get("/api/searches/:id",async(req: Request,res: Response)=>{const{ userId }=req.query;const{ id }=req.params;try{constsearch=awaitSearchModel.findOne({ userId,name: id}).exec();if(search)returnres.sendStatus(200).json(search);returnres.sendStatus(404).json({message: "Not Found!"});}catch(error){console.error('Error loading search:',error);res.sendStatus(500).json({message: "Internal Server Error!"});}});app.listen(5000,()=>{console.log("Server listening on port 5000...");});