2024-02-06 16:16:10 +11:00
|
|
|
import type { NextApiRequest, NextApiResponse } from 'next';
|
2023-10-15 20:26:32 +11:00
|
|
|
|
|
|
|
|
import { getToken } from 'next-auth/jwt';
|
|
|
|
|
import { match } from 'ts-pattern';
|
|
|
|
|
|
|
|
|
|
import { ERROR_CODES } from './errors';
|
2024-02-06 16:16:10 +11:00
|
|
|
import type { TLimitsErrorResponseSchema, TLimitsResponseSchema } from './schema';
|
2023-10-15 20:26:32 +11:00
|
|
|
import { getServerLimits } from './server';
|
|
|
|
|
|
|
|
|
|
export const limitsHandler = async (
|
|
|
|
|
req: NextApiRequest,
|
|
|
|
|
res: NextApiResponse<TLimitsResponseSchema | TLimitsErrorResponseSchema>,
|
|
|
|
|
) => {
|
|
|
|
|
try {
|
|
|
|
|
const token = await getToken({ req });
|
|
|
|
|
|
2024-02-06 16:16:10 +11:00
|
|
|
const rawTeamId = req.headers['team-id'];
|
|
|
|
|
|
|
|
|
|
let teamId: number | null = null;
|
|
|
|
|
|
|
|
|
|
if (typeof rawTeamId === 'string' && !isNaN(parseInt(rawTeamId, 10))) {
|
|
|
|
|
teamId = parseInt(rawTeamId, 10);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!teamId && rawTeamId) {
|
|
|
|
|
throw new Error(ERROR_CODES.INVALID_TEAM_ID);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const limits = await getServerLimits({ email: token?.email, teamId });
|
2023-10-15 20:26:32 +11:00
|
|
|
|
2023-10-22 11:18:00 +11:00
|
|
|
return res.status(200).json(limits);
|
2023-10-15 20:26:32 +11:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error('error', err);
|
|
|
|
|
|
|
|
|
|
if (err instanceof Error) {
|
|
|
|
|
const status = match(err.message)
|
|
|
|
|
.with(ERROR_CODES.UNAUTHORIZED, () => 401)
|
|
|
|
|
.otherwise(() => 500);
|
|
|
|
|
|
|
|
|
|
return res.status(status).json({
|
|
|
|
|
error: ERROR_CODES[err.message] ?? ERROR_CODES.UNKNOWN,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2023-11-04 13:14:20 +11:00
|
|
|
return res.status(500).json({
|
2023-10-15 20:26:32 +11:00
|
|
|
error: ERROR_CODES.UNKNOWN,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
};
|