generateApiRateLimitConfig.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { IApiRateLimitConfig } from '../interfaces/api-rate-limit-config';
  2. const getTargetFromKey = (key: string) => {
  3. return key.replace(/^API_RATE_LIMIT_/, '').replace(/_ENDPOINT$/, '');
  4. };
  5. const generateApiRateLimitConfigFromEndpoint = (envVar: NodeJS.ProcessEnv, endpointKeys: string[]): IApiRateLimitConfig => {
  6. const apiRateLimitConfig: IApiRateLimitConfig = {};
  7. endpointKeys.forEach((key) => {
  8. const endpoint = envVar[key];
  9. if (endpoint == null || Object.keys(apiRateLimitConfig).includes(endpoint)) {
  10. return;
  11. }
  12. const target = getTargetFromKey(key);
  13. const method = envVar[`API_RATE_LIMIT_${target}_METHODS`] ?? 'ALL';
  14. const maxRequests = Number(envVar[`API_RATE_LIMIT_${target}_MAX_REQUESTS`]);
  15. if (endpoint == null || maxRequests == null) {
  16. return;
  17. }
  18. const config = {
  19. method,
  20. maxRequests,
  21. };
  22. apiRateLimitConfig[endpoint] = config;
  23. });
  24. return apiRateLimitConfig;
  25. };
  26. // this method is called only one server starts
  27. export const generateApiRateLimitConfig = (): IApiRateLimitConfig => {
  28. const envVar = process.env;
  29. const apiRateEndpointKeys = Object.keys(envVar).filter((key) => {
  30. const endpointRegExp = /^API_RATE_LIMIT_\w+_ENDPOINT/;
  31. return endpointRegExp.test(key);
  32. });
  33. // sort priority
  34. apiRateEndpointKeys.sort().reverse();
  35. // get config
  36. const apiRateLimitConfig = generateApiRateLimitConfigFromEndpoint(envVar, apiRateEndpointKeys);
  37. // default setting e.g. healthchack
  38. apiRateLimitConfig['/_api/v3/healthcheck'] = {
  39. method: 'GET',
  40. maxRequests: 0,
  41. };
  42. return apiRateLimitConfig;
  43. };