| 12345678910111213141516171819202122232425262728293031323334353637 |
- const _ = require('lodash')
- const { Set } = require('immutable')
- const fillPath = (path, data) =>
- path.replace(/:(\w+)/g, (text, key) => data[key] || text)
- const diffBy = (before, after, selector) => {
- // Collect new, collect old, collect same
- const beforeDict = _.fromPairs(before.map(x => [selector(x), x]))
- const afterDict = _.fromPairs(before.map(x => [selector(x), x]))
- const beforeKeys = new Set(before.map(selector))
- const afterKeys = new Set(after.map(selector))
- const newKeys = afterKeys.subtract(beforeKeys)
- const oldKeys = beforeKeys.subtract(afterKeys)
- const commonKeys = beforeKeys.intersect(afterKeys)
- return {
- 'new': newKeys.map(key => afterDict[key]),
- old: oldKeys.map(key => beforeDict[key]),
- common: commonKeys.map(key => [beforeDict[key], afterDict[key]])
- }
- }
- const sanitize = _.curry(async (req, data) => {
- if (data) {
- if (Array.isArray(data)) return Promise.all(data.map(sanitize(req)))
- if (data.sanitize) return await data.sanitize(req)
- if (data.toJSON) return data.toJSON()
- }
- return data
- })
- module.exports = {
- fillPath,
- diffBy,
- sanitize
- }
|