Added stats & SQL order by on get points

This commit is contained in:
2024-10-16 09:35:52 +02:00
parent 8bde354b71
commit 60a7570ca2
7 changed files with 137 additions and 7 deletions
+99
View File
@@ -0,0 +1,99 @@
import { NextRequest, NextResponse } from 'next/server';
import { getDBConnexion } from '../utils';
export const GET = async (req: NextRequest) => {
const userID = req.headers.get('Authorization');
if (!userID) {
return NextResponse.json(
{
error: true,
message: 'Unauthorized request',
},
{
status: 403,
}
);
}
try {
const pool = getDBConnexion();
const { rows: userCount } = await pool.query(
`SELECT * FROM "user" WHERE "id"=$1 LIMIT 1;`,
[userID]
);
if (userCount.length != 1) {
return NextResponse.json(
{
error: true,
message: 'User not found',
},
{
status: 404,
}
);
}
const { rows } = await pool.query(
`
SELECT (
SELECT AVG(entries)
FROM (
SELECT COUNT(*) AS entries
FROM point
WHERE userid=$1
GROUP BY date_part('year', createdat)
)
) AS avgPerYear,
(
SELECT AVG(entries)
FROM (
SELECT COUNT(*) AS entries
FROM point
WHERE userid=$1
GROUP BY date_part('year', createdat), date_part('month', createdat)
)
) AS avgPerMonth,
(
SELECT AVG(entries)
FROM (
SELECT COUNT(*) AS entries
FROM point
WHERE userid=$1
GROUP BY date_part('year', createdat), date_part('month', createdat), date_part('week', createdat)
)
) AS avgPerWeek,
(
SELECT COUNT(*)
FROM point
WHERE userid=$1
) AS total;`,
[userID]
);
const result = {
year: Math.round(parseFloat(rows[0].avgperyear)),
month: Math.round(parseFloat(rows[0].avgpermonth)),
week: Math.round(parseFloat(rows[0].avgperweek)),
total: parseInt(rows[0].total),
};
await pool.end();
return NextResponse.json(result, {
status: 200,
});
} catch (error) {
console.error(error);
return NextResponse.json(
{
error: true,
message: 'Internal error',
},
{
status: 500,
}
);
}
};