Skip to content

Instantly share code, notes, and snippets.

@Bucephalus-lgtm
Created February 27, 2023 16:49
Show Gist options
  • Save Bucephalus-lgtm/b7cec60c4d0bc93b9009938191616e68 to your computer and use it in GitHub Desktop.
Save Bucephalus-lgtm/b7cec60c4d0bc93b9009938191616e68 to your computer and use it in GitHub Desktop.

The below code explains how you can write save and write API as per your requirements:

index.js
/**
 * @author: Bhargab Nath  <bhargabnath691@gmail.com>
 *
 */


import express, { Request, Response } from "express";
import mongoose from 'mongoose';
import SearchModel from './Search.model.ts';

interface Search {
  userId: string;
  name: string;
  queries: string[];
}

const app = 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));

const searches: 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) => {
  const search = req.body as Search;
  try {
    await SearchModel.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 {
    const userSearches = await SearchModel.find({ userId }).select('name').exec();
    const searchNames = userSearches.map(search => search.name);
    return res.sendStatus(200).json(searchNames);
  } catch (error) {
    console.error('Error loading searches:', error);
    return res.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 {
    const search = await SearchModel.findOne({ userId, name: id }).exec();
    if (search) return res.sendStatus(200).json(search);
    return res.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...");
});

Search.model.ts

import mongoose, { Document, Model, Schema } from 'mongoose';

interface SearchDocument extends Document {
  userId: string;
  name: string;
  queries: string[];
}

const SearchSchema = new Schema<SearchDocument>({
  userId: { type: String, required: true },
  name: { type: String, required: true },
  queries: [{ type: String }],
});

const SearchModel: Model<SearchDocument> = mongoose.model<SearchDocument>('Search', SearchSchema);

export default SearchModel;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment