Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

homework week2 #219

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions nodejs/week2/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
71 changes: 71 additions & 0 deletions nodejs/week2/app/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import express from "express";
import data from "./documents.json" assert { type: "json" };

const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());

app.get("/", (req, res) => {
res.send("This is a search engine");
});

//
app.get("/search", (req, res) => {
const { q } = req.query;
if (!q) {
return res.json(data);
}

const filteredData = data.filter((doc) =>
Object.values(doc).some((value) =>
String(value).toLowerCase().includes(q.toLowerCase())
)
);

res.json(filteredData);
});

//
app.get("/documents/:id", (req, res) => {
const searchedData = data.find((element) => element.id === req.params.id);

if (!searchedData) {
return res.status(404).json({ error: "ID not found" });
}

res.json(searchedData);
});

//
app.post("/search", (req, res) => {
const { q } = req.query;
const { fields } = req.body;

if (q && fields) {
return res.status(400).json({ error: "Cannot provide both q (query) and fields" });
}

if (q) {
const filteredData = data.filter((doc) =>
Object.values(doc).some((value) =>
String(value).toLowerCase().includes(q.toLowerCase())
)
);
return res.json(filteredData);
}

if (fields) {
const filteredData = data.filter((doc) =>
Object.entries(fields).every(([key, value]) => doc[key] == value)
);

return res.json(filteredData);
}

res.json(data);
});

app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
13 changes: 13 additions & 0 deletions nodejs/week2/app/documents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[
{
"id": 1,
"name": "Used Apple Airpods",
"price": "50",
"description": "Battery life is not great"
},
{
"id": 2,
"type": "doc",
"value": "hello world"
}
]
Loading