| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- 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 await Promise.all(data.map(sanitize(req)))
- if (data.sanitize) return await data.sanitize(req)
- if (data.toJSON) return data.toJSON()
- }
- return data
- })
- const dict = (collection) => {
- collection.forEach(item => {
- collection[item.key] = item
- collection[item.id] = item
- })
- return collection
- }
- module.exports = {
- fillPath,
- diffBy,
- sanitize,
- dict
- }
|