api-v1/routes/locationRoutes.js

137 lines
3.0 KiB
JavaScript

import express from "express";
import { Pool } from "pg";
const router = express.Router();
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD_D,
port: process.env.DB_PORT,
});
// Add a new location
router.post("/", async (req, res) => {
const {
user_id,
is_saved_address,
location_type,
country,
state,
district,
city_village,
pincode,
lat,
lng,
source_type,
source_confidence,
} = req.body;
try {
const insertQuery =
"INSERT INTO locations (user_id, is_saved_address, location_type, country, state, district, city_village, pincode, lat, lng, source_type, source_confidence) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING *";
const values = [
user_id,
is_saved_address,
location_type,
country,
state,
district,
city_village,
pincode,
lat,
lng,
source_type,
source_confidence,
];
const result = await pool.query(insertQuery, values);
res.status(201).json({
message: "Location added successfully",
location: result.rows[0],
});
} catch (error) {
console.error("Error adding location:", error);
res.status(500).json({
error: "Internal server error adding location",
});
}
});
// Update a location by ID
router.put("/:id", async (req, res) => {
const locationId = req.params.id;
const {
user_id,
is_saved_address,
location_type,
country,
state,
district,
city_village,
pincode,
lat,
lng,
source_type,
source_confidence,
} = req.body;
try {
const updateQuery =
"UPDATE locations SET user_id = $1, is_saved_address = $2, location_type = $3, country = $4, state = $5, district = $6, city_village = $7, pincode = $8, lat = $9, lng = $10, source_type = $11, source_confidence = $12 WHERE id = $13 RETURNING *";
const values = [
user_id,
is_saved_address,
location_type,
country,
state,
district,
city_village,
pincode,
lat,
lng,
source_type,
source_confidence,
locationId,
];
const result = await pool.query(updateQuery, values);
if (result.rows.length === 0) {
return res.status(404).json({ error: "Location not found" });
}
res.status(200).json({
message: "Location updated successfully",
location: result.rows[0],
});
} catch (error) {
console.error("Error updating location:", error);
res.status(500).json({
error: "Internal server error updating location",
});
}
});
// Get location by ID
router.get("/:id", async (req, res) => {
const locationId = req.params.id;
try {
const selectQuery = "SELECT * FROM locations WHERE id = $1";
const result = await pool.query(selectQuery, [locationId]);
if (result.rows.length === 0) {
return res.status(404).json({ error: "Location not found" });
}
res.status(200).json(result.rows[0]);
} catch (error) {
console.error("Error fetching location:", error);
res.status(500).json({
error: "Internal server error fetching location",
});
}
});
export default router;