Files
Lovemap/app/api/stats/route.ts
T

100 lines
1.8 KiB
TypeScript

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,
}
);
}
};