util.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. const _ = require('lodash')
  2. const { Set } = require('immutable')
  3. const fillPath = (path, data) =>
  4. path.replace(/:(\w+)/g, (text, key) => data[key] || text)
  5. const diffBy = (before, after, selector) => {
  6. // Collect new, collect old, collect same
  7. const beforeDict = _.fromPairs(before.map(x => [selector(x), x]))
  8. const afterDict = _.fromPairs(before.map(x => [selector(x), x]))
  9. const beforeKeys = new Set(before.map(selector))
  10. const afterKeys = new Set(after.map(selector))
  11. const newKeys = afterKeys.subtract(beforeKeys)
  12. const oldKeys = beforeKeys.subtract(afterKeys)
  13. const commonKeys = beforeKeys.intersect(afterKeys)
  14. return {
  15. 'new': newKeys.map(key => afterDict[key]),
  16. old: oldKeys.map(key => beforeDict[key]),
  17. common: commonKeys.map(key => [beforeDict[key], afterDict[key]])
  18. }
  19. }
  20. const sanitize = _.curry(async (req, data) => {
  21. if (data) {
  22. if (Array.isArray(data)) return Promise.all(data.map(sanitize(req)))
  23. if (data.sanitize) return await data.sanitize(req)
  24. if (data.toJSON) return data.toJSON()
  25. }
  26. return data
  27. })
  28. module.exports = {
  29. fillPath,
  30. diffBy,
  31. sanitize
  32. }