fosrl.pangolin/server/auth/limits.ts

40 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-10-06 17:42:28 -04:00
import { db } from '@server/db';
import { limitsTable } from '@server/db/schema';
import { and, eq } from 'drizzle-orm';
import createHttpError from 'http-errors';
import HttpCode from '@server/types/HttpCode';
interface CheckLimitOptions {
2024-10-06 18:05:20 -04:00
orgId: number;
limitName: string;
currentValue: number;
increment?: number;
2024-10-06 17:42:28 -04:00
}
export async function checkOrgLimit({ orgId, limitName, currentValue, increment = 0 }: CheckLimitOptions): Promise<boolean> {
2024-10-06 18:05:20 -04:00
try {
const limit = await db.select()
.from(limitsTable)
.where(
and(
eq(limitsTable.orgId, orgId),
eq(limitsTable.name, limitName)
)
)
.limit(1);
2024-10-06 17:42:28 -04:00
2024-10-06 18:05:20 -04:00
if (limit.length === 0) {
throw createHttpError(HttpCode.NOT_FOUND, `Limit "${limitName}" not found for organization`);
}
2024-10-06 17:42:28 -04:00
2024-10-06 18:05:20 -04:00
const limitValue = limit[0].value;
2024-10-06 17:42:28 -04:00
2024-10-06 18:05:20 -04:00
// Check if the current value plus the increment is within the limit
return (currentValue + increment) <= limitValue;
} catch (error) {
if (error instanceof Error) {
throw createHttpError(HttpCode.INTERNAL_SERVER_ERROR, `Error checking limit: ${error.message}`);
}
throw createHttpError(HttpCode.INTERNAL_SERVER_ERROR, 'Unknown error occurred while checking limit');
2024-10-06 17:42:28 -04:00
}
}