diff --git a/src/app/packages/page.tsx b/src/app/packages/page.tsx
index c834afb0..8a38f3f1 100644
--- a/src/app/packages/page.tsx
+++ b/src/app/packages/page.tsx
@@ -4,7 +4,6 @@ import React, { useEffect, useState, Fragment } from "react";
import statsList from "../projects/assets/stats.json";
import Link from "next/link";
import npm from "../../../public/images/social-media/npm-svgrepo-com.svg";
-import pypi from "../../../public/images/social-media/pypi-svg.svg";
import filter from "../../../public/images/social-media/bx-filter-alt.svg";
import download from "../../../public/images/bxs-download.svg";
import github from "../../../public/images/bxl-github.svg";
@@ -12,39 +11,31 @@ import Image from "next/image";
import { Dialog, Transition } from "@headlessui/react";
import moment from "moment";
-type Package = {
- name: string;
- type: "npm" | "pypi";
- day?: number;
- week?: number;
- year?: number;
- total?: number;
- last_day?: number;
- last_week?: number;
- last_month?: number;
+type stats = {
+ downloads: download[];
};
-type NpmStats = {
- downloads: { downloads: number; day: string }[];
+type download = {
+ downloads: number;
+ day: string;
};
const Stats = () => {
const [startDate, setStartDate] = useState(moment().format("YYYY-MM-DD"));
const [endDate, setEndDate] = useState(moment().format("YYYY-MM-DD"));
- const [loading, setLoading] = useState(false);
+ const [loading, setLoading] = useState(false); // State to track loading status
const [count, setCount] = useState(0);
const [selectedRange, setSelectedRange] = useState(false);
const [isOpen, setIsOpen] = useState(false);
- const [selectedPackage, setSelectedPackage] = useState({
+ const [npmPackage, setNpmPackage] = useState({
name: "fmdapi-node-weaver",
- type: "npm",
day: 0,
week: 3,
year: 70,
total: 70,
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
- const [packages, setPackages] = useState(statsList as Package[]);
+ const [packages, setPackages] = useState(statsList);
function closeModal() {
setIsOpen(false);
@@ -52,28 +43,18 @@ const Stats = () => {
}
useEffect(() => {
- if (selectedPackage) {
- setCount(
- selectedPackage.type === "npm"
- ? selectedPackage.total || 0
- : selectedPackage.last_month || 0
- ); //update total count when npmPackage is updated
+ if (npmPackage) {
+ setCount(npmPackage.total); //update total count when npmPackage is updated
}
- }, [selectedPackage]);
+ }, [npmPackage]);
function openModal() {
setIsOpen(true);
- setCount(
- selectedPackage.type === "npm"
- ? selectedPackage.total || 0
- : selectedPackage.last_month || 0
- );
+ setCount(npmPackage.total);
}
- async function fetchNpmStats(
- packageName: string,
- period: string
- ): Promise {
+ // Function to fetch download statistics for a given package and period
+ async function fetchDownloadStats(packageName: string, period: string) {
setLoading(true);
const url = `https://api.npmjs.org/downloads/range/${period}/@mindfiredigital/${packageName}`;
const response = await fetch(url);
@@ -83,7 +64,6 @@ const Stats = () => {
`Failed to fetch download stats for ${packageName} (${period}): ${response.statusText}`
);
setLoading(false);
- throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
@@ -91,37 +71,67 @@ const Stats = () => {
return data;
}
- function calculateDownloads(stats: NpmStats): number {
+ function calculateDownloads(stats: stats): number {
if (!stats || !stats.downloads) {
- return 0;
+ return 0; // Return 0 if stats or stats.downloads is undefined
}
return stats.downloads.reduce(
- (acc, download) => acc + download.downloads,
+ (accumulator, download) => accumulator + download.downloads,
0
);
}
- function handleChange(event: React.ChangeEvent) {
- if (!selectedPackage) return;
+ // Function to fetch and process statistics for a package and period
+ async function getStats(packageName: string, period: string) {
+ try {
+ // Fetch download statistics
+ const stats = await fetchDownloadStats(packageName, period);
+
+ // Check if stats exist
+ if (!stats || !stats.package) return 0;
+
+ // Calculate average downloads
+ return stats;
+ } catch (error) {
+ // Log and handle errors
+ console.error(`${packageName} not present`);
+ return 0;
+ }
+ }
+ function handleChange(
+ event: React.ChangeEvent,
+ _package: {
+ name: string;
+ day: number;
+ week: number;
+ year: number;
+ total: number;
+ }
+ ) {
+ const range: { start: string; end: string } = getDateRange(
+ event.target.value as string
+ );
- const range = getDateRange(event.target.value);
+ getStats(_package.name, `${range?.start}:${range?.end}`).then((res) => {
+ setLoading(true);
+ const count = calculateDownloads(res);
+ // console.log(count);
- if (selectedPackage.type === "npm") {
- fetchNpmStats(selectedPackage.name, `${range.start}:${range.end}`).then(
- (res) => {
- setLoading(true);
- const count = calculateDownloads(res);
+ packages.map((npmPackage) => {
+ if (npmPackage.name === _package.name) {
setCount(count);
setLoading(false);
}
- );
- } else if (selectedPackage.type === "pypi") {
- setCount(Number(event.target.value) || 0);
- }
+ return npmPackage;
+ });
+ });
}
function formatDate(date: Date) {
- return date.toISOString().split("T")[0];
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, "0");
+ const day = String(date.getDate()).padStart(2, "0");
+ return `${year}-${month}-${day}`;
}
function getDateRange(range: string) {
@@ -131,12 +141,13 @@ const Stats = () => {
const currentDay = currentDate.getDate();
switch (range.toLowerCase()) {
- case "today":
+ case "today": {
setSelectedRange(false);
return {
start: formatDate(new Date(currentYear, currentMonth, currentDay)),
end: formatDate(new Date(currentYear, currentMonth, currentDay)),
};
+ }
case "yesterday": {
setSelectedRange(false);
const yesterdayDate = new Date(
@@ -158,17 +169,9 @@ const Stats = () => {
end: formatDate(lastMonthEndDate),
};
}
- case "this month": {
- setSelectedRange(false);
- const thisMonthStartDate = new Date(currentYear, currentMonth, 1);
- return {
- start: formatDate(thisMonthStartDate),
- end: formatDate(currentDate),
- };
- }
case "last quarter": {
setSelectedRange(false);
- const quarterStartMonth = Math.floor(currentMonth / 3) * 3;
+ const quarterStartMonth = Math.floor(currentMonth / 3) * 3; // Get the start month of the current quarter
const lastQuarterStartDate = new Date(
currentYear,
quarterStartMonth - 3,
@@ -188,6 +191,14 @@ const Stats = () => {
end: formatDate(currentDate),
};
}
+ case "this month": {
+ setSelectedRange(false);
+ const thisMonthStartDate = new Date(currentYear, currentMonth, 1);
+ return {
+ start: formatDate(thisMonthStartDate),
+ end: formatDate(currentDate),
+ };
+ }
case "custom": {
setSelectedRange(true);
setCount(0);
@@ -196,34 +207,26 @@ const Stats = () => {
end: formatDate(new Date(currentYear, currentMonth, currentDay)),
};
}
- default: {
+ default:
setSelectedRange(false);
return {
start: "1000-01-01",
end: "3000-01-01",
};
- }
}
}
- console.log("selecyed package 1", selectedPackage);
+
const generateChart = async () => {
- if (selectedPackage.type === "npm") {
- const stats = await fetchNpmStats(
- selectedPackage.name,
- `${startDate}:${endDate}`
- );
- setCount(calculateDownloads(stats));
- }
+ const stats = await fetchDownloadStats(
+ npmPackage.name,
+ `${startDate}:${endDate}`
+ );
+ setCount(calculateDownloads(stats));
};
- console.log("selecyed package 2", selectedPackage);
useEffect(() => {
- console.log("selecyed package 3", selectedPackage);
-
- if (selectedRange && selectedPackage.type === "npm") {
- generateChart();
- }
- }, [startDate, endDate, selectedRange, selectedPackage]);
+ generateChart();
+ }, [startDate, endDate]);
return (
@@ -235,16 +238,16 @@ const Stats = () => {
Elevate your projects with Mindfire's game-changing open-source
packages.
-
- {packages.map((package_item) => (
+
+ {packages.map((package_list) => (
- {package_item.name.replaceAll("-", " ")}
+ {package_list.name.replaceAll("-", " ")}
@@ -252,7 +255,7 @@ const Stats = () => {
@@ -297,19 +298,15 @@ const Stats = () => {
@@ -317,7 +314,7 @@ const Stats = () => {
@@ -325,7 +322,7 @@ const Stats = () => {
src={github}
height={30}
width={30}
- alt='github_img'
+ alt='npm_img'
loading='lazy'
quality={75}
/>
@@ -388,45 +385,31 @@ const Stats = () => {
as='h1'
className='text-lg font-large leading-6 text-gray-900 capitalize text-center mb-4 font-extrabold'
>
- {selectedPackage.name.replaceAll("-", " ")}
+ {npmPackage.name.replaceAll("-", " ")}
-
+
Select
- {selectedPackage.type === "npm" ? (
-
- ) : (
-
- )}
+
- {selectedRange && selectedPackage.type === "npm" ? (
-
+ {selectedRange === true ? (
+
- ) : null}
-
-
-
-
-
-
- {loading ? (
-
-
+
+
+
+
+
+
+ {loading ? (
+ // Render loading indicator while count is being fetched
+
+
+
+ ) : (
+ // Render count when it is available
+
+ {count}
+
+ )}
- ) : (
-
- {count}
-
- )}
+
+
-
+
+ ) : (
+
+
+
+
+
+
+ {loading ? (
+ // Render loading indicator while count is being fetched
+
+
+
+ ) : (
+ // Render count when it is available
+
+ {count}
+
+ )}
+
+
+
-
+ )}
diff --git a/src/app/projects/assets/stats.json b/src/app/projects/assets/stats.json
index f7b2e4f1..e03009ca 100644
--- a/src/app/projects/assets/stats.json
+++ b/src/app/projects/assets/stats.json
@@ -1,7 +1,6 @@
[
{
"name": "fmdapi-node-weaver",
- "type": "npm",
"day": 0,
"week": 3,
"year": 70,
@@ -9,7 +8,6 @@
},
{
"name": "react-canvas-editor",
- "type": "npm",
"day": 1,
"week": 22,
"year": 947,
@@ -17,17 +15,9 @@
},
{
"name": "canvas-editor",
- "type": "npm",
"day": 0,
"week": 7,
"year": 1063,
"total": 1063
- },
- {
- "name": "neo-pusher",
- "type": "pypi",
- "last_day": 1,
- "last_week": 70,
- "last_month": 1000
}
]
diff --git a/updateProject.mjs b/updateProject.mjs
index 40278731..40569664 100644
--- a/updateProject.mjs
+++ b/updateProject.mjs
@@ -221,39 +221,6 @@ async function fetchDownloadStats(packageName, period) {
return data;
}
-// Function to fetch download statistics for a PyPI package
-async function fetchPypiDownloadStats(packageName) {
- const url = `https://pypistats.org/api/packages/${packageName}/recent`;
- const response = await fetch(url);
-
- if (!response.ok) {
- console.log(
- `Failed to fetch download stats for ${packageName}: ${response.statusText}`
- );
- return null;
- }
-
- const data = await response.json();
- return data.data;
-}
-
-// Function to fetch and process statistics for a PyPI package
-async function getPypiStats(packageName) {
- try {
- const stats = await fetchPypiDownloadStats(packageName);
- if (!stats) return null;
-
- return {
- last_day: stats.data.last_day,
- last_week: stats.data.last_week,
- last_month: stats.data.last_month,
- };
- } catch (error) {
- console.error(`Error fetching PyPI stats for ${packageName}:`, error);
- return null;
- }
-}
-
// Function to calculate average downloads from the statistics
function calculateAverageDownloads(stats) {
return stats.downloads.reduce(
@@ -286,40 +253,29 @@ async function getAllStats(npmPackages) {
// Fetch stats for each package and period
await Promise.all(
- npmPackages.map(async (packageData) => {
+ npmPackages.map(async (packageName) => {
try {
- let stats;
- if (packageData.type === "npm") {
- const [dayStats, weekStats, yearStats, totalStats] =
- await Promise.all([
- getStats(packageData.name, "last-day"),
- getStats(packageData.name, "last-week"),
- getStats(packageData.name, "last-year"),
- getStats(packageData.name, "1000-01-01:3000-01-01"),
- ]);
-
- stats = {
- name: packageData.name,
- type: "npm",
+ // Fetch stats for different periods
+ const [dayStats, weekStats, yearStats, totalStats] = await Promise.all([
+ getStats(packageName, "last-day"),
+ getStats(packageName, "last-week"),
+ getStats(packageName, "last-year"),
+ getStats(packageName, "1000-01-01:3000-01-01"),
+ ]);
+
+ // If any stats exist, add to the map
+ if (dayStats !== 0 || weekStats !== 0 || yearStats !== 0) {
+ statsMap.push({
+ name: packageName,
day: dayStats,
week: weekStats,
year: yearStats,
total: totalStats,
- };
- } else if (packageData.type === "pypi") {
- const pypiStats = await getPypiStats(packageData.name);
- stats = {
- name: packageData.name,
- type: "pypi",
- ...pypiStats,
- };
- }
-
- if (stats) {
- statsMap.push(stats);
+ });
}
} catch (error) {
- console.error(`Error fetching stats for ${packageData.name}:`, error);
+ // Log and handle errors
+ console.error(`Error fetching stats for ${packageName}:`, error);
}
})
);