generateApiRateLimitConfig.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { IApiRateLimitConfig } from '../../interfaces/api-rate-limit-config';
  2. import { defaultConfigWithoutRegExp, defaultConfigWithRegExp } from './defaultApiRateLimitConfig';
  3. const envVar = process.env;
  4. const getTargetFromKey = (key: string, withRegExp: boolean): string|null => {
  5. const regExp = new RegExp(withRegExp ? '^API_RATE_LIMIT_|_ENDPOINT_WITH_REGEXP$' : '^API_RATE_LIMIT_|_ENDPOINT$', 'g');
  6. if (!regExp.test(key)) {
  7. return null;
  8. }
  9. const target = key.replaceAll(regExp, '');
  10. return target;
  11. };
  12. const generateApiRateLimitConfigFromEndpoint = (envVar: NodeJS.ProcessEnv, targets: string[], withRegExp: boolean): IApiRateLimitConfig => {
  13. const apiRateLimitConfig: IApiRateLimitConfig = {};
  14. targets.forEach((target) => {
  15. const endpointKey = withRegExp ? `API_RATE_LIMIT_${target}_ENDPOINT_WITH_REGEXP` : `API_RATE_LIMIT_${target}_ENDPOINT`;
  16. const endpoint = envVar[endpointKey];
  17. if (endpoint == null) {
  18. return;
  19. }
  20. const methodKey = `API_RATE_LIMIT_${target}_METHODS`;
  21. const maxRequestsKey = `API_RATE_LIMIT_${target}_MAX_REQUESTS`;
  22. const method = envVar[methodKey] ?? 'ALL';
  23. const maxRequests = Number(envVar[maxRequestsKey]);
  24. if (endpoint == null || maxRequests == null) {
  25. return;
  26. }
  27. const config = {
  28. method,
  29. maxRequests,
  30. };
  31. apiRateLimitConfig[endpoint] = config;
  32. });
  33. return apiRateLimitConfig;
  34. };
  35. export const generateApiRateLimitConfig = (withRegExp: boolean): IApiRateLimitConfig => {
  36. const apiRateConfigTargets: string[] = [];
  37. Object.keys(envVar).forEach((key) => {
  38. const target = getTargetFromKey(key, withRegExp);
  39. if (target == null) {
  40. return;
  41. }
  42. apiRateConfigTargets.push(target);
  43. });
  44. // sort priority
  45. apiRateConfigTargets.sort();
  46. // get config
  47. const apiRateLimitConfig = generateApiRateLimitConfigFromEndpoint(envVar, apiRateConfigTargets, withRegExp);
  48. const defaultConfig = withRegExp ? defaultConfigWithRegExp : defaultConfigWithoutRegExp;
  49. return { ...defaultConfig, ...apiRateLimitConfig };
  50. };