adapters.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. function maxFileSizeUnitTransform(maxLogSize) {
  3. if (typeof maxLogSize === 'number' && Number.isInteger(maxLogSize)) {
  4. return maxLogSize;
  5. }
  6. const units = {
  7. K: 1024,
  8. M: 1024 * 1024,
  9. G: 1024 * 1024 * 1024,
  10. };
  11. const validUnit = Object.keys(units);
  12. const unit = maxLogSize.substr(maxLogSize.length - 1).toLocaleUpperCase();
  13. const value = maxLogSize.substring(0, maxLogSize.length - 1).trim();
  14. if (validUnit.indexOf(unit) < 0 || !Number.isInteger(Number(value))) {
  15. throw Error(`maxLogSize: "${maxLogSize}" is invalid`);
  16. } else {
  17. return value * units[unit];
  18. }
  19. }
  20. function adapter(configAdapter, config) {
  21. const newConfig = Object.assign({}, config);
  22. Object.keys(configAdapter).forEach((key) => {
  23. if (newConfig[key]) {
  24. newConfig[key] = configAdapter[key](config[key]);
  25. }
  26. });
  27. return newConfig;
  28. }
  29. function fileAppenderAdapter(config) {
  30. const configAdapter = {
  31. maxLogSize: maxFileSizeUnitTransform
  32. };
  33. return adapter(configAdapter, config);
  34. }
  35. const adapters = {
  36. file: fileAppenderAdapter,
  37. fileSync: fileAppenderAdapter
  38. };
  39. module.exports.modifyConfig = config => (adapters[config.type] ? adapters[config.type](config) : config);