Skip to content

Real-time dashboard for monitoring global news, markets, and geopolitical events

TypeScript

Simplify and refactor recent code changes

Sean Thielen-Esparzaed0b4cbf5efc
diff --git a/.gitignore b/.gitignore
index ecd5a8c..6a74033 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,3 +30,9 @@ npm-debug.log*
# OS files
Thumbs.db
+
+# Playwright MCP screenshots
+.playwright-mcp/
+
+# Archive folder
+archive/
diff --git a/src/lib/api/markets.ts b/src/lib/api/markets.ts
index 3b8fc5c..6668d8a 100644
--- a/src/lib/api/markets.ts
+++ b/src/lib/api/markets.ts
@@ -36,6 +36,24 @@ function hasFinnhubApiKey(): boolean {
return Boolean(FINNHUB_API_KEY && FINNHUB_API_KEY.length > 0);
}
+/**
+ * Create an empty market item (used for error/missing data states)
+ */
+function createEmptyMarketItem<T extends 'index' | 'commodity'>(
+ symbol: string,
+ name: string,
+ type: T
+): MarketItem {
+ return { symbol, name, price: NaN, change: NaN, changePercent: NaN, type };
+}
+
+/**
+ * Create an empty sector performance item
+ */
+function createEmptySectorItem(symbol: string, name: string): SectorPerformance {
+ return { symbol, name, price: NaN, change: NaN, changePercent: NaN };
+}
+
// Map index symbols to ETF proxies (free tier doesn't support direct indices)
const INDEX_ETF_MAP: Record<string, string> = {
'^DJI': 'DIA', // Dow Jones -> SPDR Dow Jones ETF
@@ -117,22 +135,17 @@ export async function fetchCryptoPrices(): Promise<CryptoItem[]> {
* Fetch market indices from Finnhub
*/
export async function fetchIndices(): Promise<MarketItem[]> {
+ const createEmptyIndices = () =>
+ INDICES.map((i) => createEmptyMarketItem(i.symbol, i.name, 'index'));
+
if (!hasFinnhubApiKey()) {
logger.warn('Markets API', 'Finnhub API key not configured. Add VITE_FINNHUB_API_KEY to .env');
- return INDICES.map((index) => ({
- symbol: index.symbol,
- name: index.name,
- price: NaN,
- change: NaN,
- changePercent: NaN,
- type: 'index' as const
- }));
+ return createEmptyIndices();
}
try {
logger.log('Markets API', 'Fetching indices from Finnhub');
- // Fetch all indices in parallel (using ETF proxies)
const quotes = await Promise.all(
INDICES.map(async (index) => {
const etfSymbol = INDEX_ETF_MAP[index.symbol] || index.symbol;
@@ -151,14 +164,7 @@ export async function fetchIndices(): Promise<MarketItem[]> {
}));
} catch (error) {
logger.error('Markets API', 'Error fetching indices:', error);
- return INDICES.map((index) => ({
- symbol: index.symbol,
- name: index.name,
- price: NaN,
- change: NaN,
- changePercent: NaN,
- type: 'index' as const
- }));
+ return createEmptyIndices();
}
}
@@ -166,21 +172,17 @@ export async function fetchIndices(): Promise<MarketItem[]> {
* Fetch sector performance from Finnhub (using sector ETFs)
*/
export async function fetchSectorPerformance(): Promise<SectorPerformance[]> {
+ const createEmptySectors = () =>
+ SECTORS.map((s) => createEmptySectorItem(s.symbol, s.name));
+
if (!hasFinnhubApiKey()) {
logger.warn('Markets API', 'Finnhub API key not configured');
- return SECTORS.map((sector) => ({
- symbol: sector.symbol,
- name: sector.name,
- price: NaN,
- change: NaN,
- changePercent: NaN
- }));
+ return createEmptySectors();
}
try {
logger.log('Markets API', 'Fetching sector performance from Finnhub');
- // Fetch all sector ETFs in parallel
const quotes = await Promise.all(
SECTORS.map(async (sector) => {
const quote = await fetchFinnhubQuote(sector.symbol);
@@ -197,13 +199,7 @@ export async function fetchSectorPerformance(): Promise<SectorPerformance[]> {
}));
} catch (error) {
logger.error('Markets API', 'Error fetching sectors:', error);
- return SECTORS.map((sector) => ({
- symbol: sector.symbol,
- name: sector.name,
- price: NaN,
- change: NaN,
- changePercent: NaN
- }));
+ return createEmptySectors();
}
}
@@ -221,22 +217,17 @@ const COMMODITY_SYMBOL_MAP: Record<string, string> = {
* Fetch commodities from Finnhub
*/
export async function fetchCommodities(): Promise<MarketItem[]> {
+ const createEmptyCommodities = () =>
+ COMMODITIES.map((c) => createEmptyMarketItem(c.symbol, c.name, 'commodity'));
+
if (!hasFinnhubApiKey()) {
logger.warn('Markets API', 'Finnhub API key not configured');
- return COMMODITIES.map((commodity) => ({
- symbol: commodity.symbol,
- name: commodity.name,
- price: NaN,
- change: NaN,
- changePercent: NaN,
- type: 'commodity' as const
- }));
+ return createEmptyCommodities();
}
try {
logger.log('Markets API', 'Fetching commodities from Finnhub');
- // Fetch all commodities in parallel
const quotes = await Promise.all(
COMMODITIES.map(async (commodity) => {
const finnhubSymbol = COMMODITY_SYMBOL_MAP[commodity.symbol] || commodity.symbol;
@@ -255,21 +246,21 @@ export async function fetchCommodities(): Promise<MarketItem[]> {
}));
} catch (error) {
logger.error('Markets API', 'Error fetching commodities:', error);
- return COMMODITIES.map((commodity) => ({
- symbol: commodity.symbol,
- name: commodity.name,
- price: NaN,
- change: NaN,
- changePercent: NaN,
- type: 'commodity' as const
- }));
+ return createEmptyCommodities();
}
}
+interface AllMarketsData {
+ crypto: CryptoItem[];
+ indices: MarketItem[];
+ sectors: SectorPerformance[];
+ commodities: MarketItem[];
+}
+
/**
* Fetch all market data
*/
-export async function fetchAllMarkets() {
+export async function fetchAllMarkets(): Promise<AllMarketsData> {
const [crypto, indices, sectors, commodities] = await Promise.all([
fetchCryptoPrices(),
fetchIndices(),
diff --git a/src/lib/api/news.ts b/src/lib/api/news.ts
index fd93ed2..90fa2fb 100644
--- a/src/lib/api/news.ts
+++ b/src/lib/api/news.ts
@@ -147,25 +147,23 @@ export async function fetchCategoryNews(category: NewsCategory): Promise<NewsIte
}
}
+/** All news categories in fetch order */
+const NEWS_CATEGORIES: NewsCategory[] = ['politics', 'tech', 'finance', 'gov', 'ai', 'intel'];
+
+/** Create an empty news result object */
+function createEmptyNewsResult(): Record<NewsCategory, NewsItem[]> {
+ return { politics: [], tech: [], finance: [], gov: [], ai: [], intel: [] };
+}
+
/**
* Fetch all news - sequential with delays to avoid rate limiting
*/
export async function fetchAllNews(): Promise<Record<NewsCategory, NewsItem[]>> {
- const categories: NewsCategory[] = ['politics', 'tech', 'finance', 'gov', 'ai', 'intel'];
- const result: Record<NewsCategory, NewsItem[]> = {
- politics: [],
- tech: [],
- finance: [],
- gov: [],
- ai: [],
- intel: []
- };
+ const result = createEmptyNewsResult();
- // Fetch categories sequentially with delay between each
- for (let i = 0; i < categories.length; i++) {
- const category = categories[i];
+ for (let i = 0; i < NEWS_CATEGORIES.length; i++) {
+ const category = NEWS_CATEGORIES[i];
- // Add delay between requests (not before the first one)
if (i > 0) {
await delay(API_DELAYS.betweenCategories);
}
diff --git a/src/lib/components/panels/IntelPanel.svelte b/src/lib/components/panels/IntelPanel.svelte
index dfa22c0..847f5c7 100644
--- a/src/lib/components/panels/IntelPanel.svelte
+++ b/src/lib/components/panels/IntelPanel.svelte
@@ -18,10 +18,8 @@
isPriority?: boolean;
}
- // Subscribe to intel news store directly
- const storeItems = $derived($intelNews.items);
- const loading = $derived($intelNews.loading);
- const error = $derived($intelNews.error);
+ // Destructure store state for cleaner access
+ const { items: storeItems, loading, error } = $derived($intelNews);
// Infer source type from source name
function inferSourceType(source: string): SourceType {
@@ -52,19 +50,16 @@
const items = $derived(storeItems.map(transformToIntelItem));
const count = $derived(items.length);
- function getSourceBadgeVariant(
- type: string
- ): 'default' | 'success' | 'warning' | 'danger' | 'info' {
- switch (type) {
- case 'osint':
- return 'info';
- case 'govt':
- return 'warning';
- case 'cyber':
- return 'danger';
- default:
- return 'default';
- }
+ type BadgeVariant = 'default' | 'success' | 'warning' | 'danger' | 'info';
+
+ const SOURCE_BADGE_VARIANTS: Record<string, BadgeVariant> = {
+ osint: 'info',
+ govt: 'warning',
+ cyber: 'danger'
+ };
+
+ function getSourceBadgeVariant(type: string): BadgeVariant {
+ return SOURCE_BADGE_VARIANTS[type] ?? 'default';
}
</script>
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 29ecda3..ff89b9e 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -20,7 +20,7 @@
IntelPanel,
SituationPanel,
WorldLeadersPanel,
- PrinterPanel
+ PrinterPanel
} from '$lib/components/panels';
import {
news,
@@ -46,6 +46,7 @@
} from '$lib/api';
import type { Prediction, WhaleTransaction, Contract, Layoff } from '$lib/api';
import type { CustomMonitor, WorldLeader } from '$lib/types';
+ import type { PanelId } from '$lib/config';
// Modal state
let settingsOpen = $state(false);
@@ -159,8 +160,9 @@
}
// Get panel visibility
- const isPanelVisible = (id: string) =>
- $settings.enabled[id as keyof typeof $settings.enabled] !== false;
+ function isPanelVisible(id: PanelId): boolean {
+ return $settings.enabled[id] !== false;
+ }
// Handle preset selection from onboarding
function handleSelectPreset(presetId: string) {