util.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 await 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. const dict = (collection, fields) => {
  29. collection.forEach(item => {
  30. collection[item.key] = item
  31. collection[item.id] = item
  32. if (Array.isArray(fields)) {
  33. fields.forEach(field => collection[item[field]] = field)
  34. }
  35. })
  36. return collection
  37. }
  38. module.exports = {
  39. fillPath,
  40. diffBy,
  41. sanitize,
  42. dict
  43. }