adapters.js 1.2 KB

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