generateApiRateLimitConfig.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 sortApiRateEndpointKeys = (endpoints: string[]): string[] => {
  6. return endpoints.sort((a, b) => {
  7. const targetA = getTargetFromKey(a);
  8. const priorityA = Number(targetA.split('_')[0]);
  9. const targetB = getTargetFromKey(b);
  10. const priorityB = Number(targetB.split('_')[0]);
  11. if (Number.isNaN(priorityA) || Number.isNaN(priorityB)) {
  12. return 1;
  13. }
  14. if (priorityA > priorityB) {
  15. return -1;
  16. }
  17. return 1;
  18. });
  19. };
  20. const generateApiRateLimitConfigFromEndpoint = (envVar: NodeJS.ProcessEnv, endpointKeys: string[]): IApiRateLimitConfig => {
  21. const apiRateLimitConfig: IApiRateLimitConfig = {};
  22. endpointKeys.forEach((key) => {
  23. const endpoint = envVar[key];
  24. if (endpoint == null || Object.keys(apiRateLimitConfig).includes(endpoint)) {
  25. return;
  26. }
  27. const target = getTargetFromKey(key);
  28. const method = envVar[`API_RATE_LIMIT_${target}_METHODS`] ?? 'ALL';
  29. const consumePoints = Number(envVar[`API_RATE_LIMIT_${target}_CONSUME_POINTS`]);
  30. if (endpoint == null || consumePoints == null) {
  31. return;
  32. }
  33. const config = {
  34. method,
  35. consumePoints,
  36. };
  37. apiRateLimitConfig[endpoint] = config;
  38. });
  39. return apiRateLimitConfig;
  40. };
  41. // this method is called only one server starts
  42. export const generateApiRateLimitConfig = (): IApiRateLimitConfig => {
  43. const envVar = process.env;
  44. const apiRateEndpointKeys = Object.keys(envVar).filter((key) => {
  45. const endpointRegExp = /^API_RATE_LIMIT_\w+_ENDPOINT/;
  46. return endpointRegExp.test(key);
  47. });
  48. // sort priority
  49. const apiRateEndpointKeysSorted = sortApiRateEndpointKeys(apiRateEndpointKeys);
  50. // get config
  51. const apiRateLimitConfig = generateApiRateLimitConfigFromEndpoint(envVar, apiRateEndpointKeysSorted);
  52. // default setting e.g. healthchack
  53. apiRateLimitConfig['/_api/v3/healthcheck'] = {
  54. method: 'GET',
  55. consumePoints: 0,
  56. };
  57. return apiRateLimitConfig;
  58. };