Selaa lähdekoodia

add price history component

Daniel Bohry 9 kuukautta sitten
vanhempi
sitoutus
02aef7185c
2 muutettua tiedostoa jossa 92 lisäystä ja 0 poistoa
  1. 88 0
      src/components/StockPriceHistory.svelte
  2. 4 0
      src/routes/stocks/[code]/+page.svelte

+ 88 - 0
src/components/StockPriceHistory.svelte

@@ -0,0 +1,88 @@
+<script>
+	import { onMount } from 'svelte';
+	import { Chart, registerables } from 'chart.js';
+	import { getRequest } from '../utils/api.js';
+
+	Chart.register(...registerables);
+
+	export let code;
+
+	let chartCanvas;
+	let chartInstance;
+
+	const endpoint = `https://stocks-be.lhamacorp.com/api/stocks/${code}/history`;
+
+	async function fetchData() {
+		try {
+			const res = await getRequest(endpoint, {}, null);
+			if (!res.ok) {
+				console.error(`Failed to fetch price history: ${res.status}`);
+				return [];
+			}
+			return await res.json();
+		} catch (err) {
+			console.error('Error fetching stock history:', err);
+			return [];
+		}
+	}
+
+	function renderChart(data) {
+		const labels = data.map(item => new Date(item.createdAt).toLocaleDateString());
+		const prices = data.map(item => item.price);
+
+		if (chartInstance) {
+			chartInstance.destroy();
+		}
+
+		chartInstance = new Chart(chartCanvas, {
+			type: 'line',
+			data: {
+				labels,
+				datasets: [
+					{
+						label: `Price (${data[0]?.currency || ''})`,
+						data: prices,
+						fill: false,
+						borderWidth: 2
+					}
+				]
+			},
+			options: {
+				responsive: true,
+				scales: {
+					x: {
+						title: {
+							display: true,
+							text: 'Date'
+						}
+					},
+					y: {
+						title: {
+							display: true,
+							text: 'Price'
+						}
+					}
+				},
+				plugins: {
+					legend: {
+						display: true
+					}
+				}
+			}
+		});
+	}
+
+	onMount(async () => {
+		if (!code) return;
+
+		const history = await fetchData();
+		if (history.length > 0) {
+			renderChart(history);
+		}
+	});
+</script>
+
+<div class="w-full mt-10 max-w-6xl mx-auto bg-white dark:bg-gray-900 p-6 rounded-xl shadow-md">
+	<h3 class="text-xl font-semibold text-gray-800 dark:text-gray-100 mb-4">Price History</h3>
+	<canvas bind:this={chartCanvas}></canvas>
+</div>

+ 4 - 0
src/routes/stocks/[code]/+page.svelte

@@ -2,6 +2,7 @@
 	import { page } from '$app/stores';
 	import { onMount } from 'svelte';
 	import { getRequest } from '../../../utils/api.js';
+	import StockPriceHistory from '../../../components/StockPriceHistory.svelte';
 
 	let code = '';
 	let stockInfo = null;
@@ -171,4 +172,7 @@
 			View More
 		</a>
 	</div>
+
+	<StockPriceHistory code={stockInfo.code} />
+
 {/if}