diff --git a/app.js b/app.js index 5ab128e4b..3cbb07366 100644 --- a/app.js +++ b/app.js @@ -1,21 +1,116 @@ const express = require("express"); +const axios = require("axios"); +const cheerio = require("cheerio"); + const app = express(); const port = process.env.PORT || 3001; -app.get("/", (req, res) => res.type('html').send(html)); +// API Endpoint to Fetch Trades from Capitol Trades +const URL = "https://www.capitoltrades.com/trades?txDate=365d"; + +async function fetchTrades() { + try { + const response = await axios.get(URL, { + headers: { + "User-Agent": "Mozilla/5.0" + } + }); + + const html = response.data; + const $ = cheerio.load(html); + const trades = []; + + $(".trade-item").each((index, element) => { + const legislator = $(element).find(".legislator-name").text().trim(); + const ticker = $(element).find(".ticker-symbol").text().trim(); + const transaction = $(element).find(".transaction-type").text().trim(); + const date = $(element).find(".trade-date").text().trim(); + const amount = $(element).find(".amount").text().trim(); + + if (legislator && ticker && transaction && date && amount) { + trades.push({ + legislator, + ticker, + transaction, + date, + amount, + }); + } + }); + + return trades; + } catch (error) { + console.error("Error fetching trade data:", error); + return []; + } +} + +// API Route for Trade Data (Searchable) +app.get("/trades", async (req, res) => { + const { legislator, ticker, transaction } = req.query; + let trades = await fetchTrades(); -const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`)); + // Filter Results Based on Query Params + if (legislator) { + trades = trades.filter(trade => trade.legislator.toLowerCase().includes(legislator.toLowerCase())); + } + if (ticker) { + trades = trades.filter(trade => trade.ticker.toLowerCase() === ticker.toLowerCase()); + } + if (transaction) { + trades = trades.filter(trade => trade.transaction.toLowerCase() === transaction.toLowerCase()); + } + res.json({ total: trades.length, trades }); +}); + +// Serve Frontend HTML with Search Integration +app.get("/", (req, res) => { + res.type("html").send(html); +}); + +const server = app.listen(port, () => console.log(`Server running on http://localhost:${port}`)); server.keepAliveTimeout = 120 * 1000; server.headersTimeout = 120 * 1000; +// Frontend HTML with Search Functionality const html = ` - Hello from Render! + Congress Trades Dashboard -
- Hello from Render! -
+

Congress Trades Dashboard

+ +
+ + + + +
+ +
+

Enter a search term and click "Search" to see results.

+
-` +`;