38 lines
1.1 KiB
JavaScript
38 lines
1.1 KiB
JavaScript
const query = require("../db.js");
|
|
const { toSnakeCase } = require("./utils.js");
|
|
|
|
const searchData = async (req, res) => {
|
|
try {
|
|
const { tableName, fieldName, value } = req.params;
|
|
const dBtableName = toSnakeCase(tableName);
|
|
|
|
const tableCheck = await query(`
|
|
SELECT EXISTS (SELECT 1 FROM pg_tables WHERE tablename = $1)
|
|
AS table_exists`, [dBtableName]);
|
|
if (!tableCheck.rows[0]["table_exists"]) {
|
|
return res.status(404).json({ error: `Data collection ${tableName} not found.` });
|
|
}
|
|
|
|
const result = await query(`
|
|
SELECT data
|
|
FROM ${dBtableName}
|
|
WHERE data['${fieldName}'] = '"${value}"'
|
|
ORDER BY data['${value}']`);
|
|
|
|
if (result.rows.length > 0) {
|
|
const data = result.rows.map(row => row.data);
|
|
res.status(200).json(data);
|
|
} else {
|
|
res.status(404).json({ message: "Not found." });
|
|
}
|
|
|
|
} catch (err) {
|
|
console.error("Error handling the request:", err);
|
|
res
|
|
.status(500)
|
|
.json({ error: "An error occurred while processing the request" });
|
|
}
|
|
};
|
|
|
|
module.exports = searchData;
|