index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import _ from "lodash-es"
  2. export async function generateTaxonomy({ config: actionConfig }) {
  3. if (!Array.isArray(actionConfig.inputs)) {
  4. return {
  5. detail: actionConfig.indexOn ? {} : [],
  6. ref: actionConfig.name,
  7. }
  8. }
  9. const orderBy = actionConfig.orderBy || "date"
  10. const inputs = actionConfig.inputs
  11. const sortedInputs = actionConfig.sortAscending
  12. ? _.sortBy(inputs, orderBy)
  13. : _.sortBy(inputs, orderBy).reverse()
  14. const buildEntry = item => actionConfig.properties
  15. ? actionConfig.properties.reduce(
  16. (ent, prop) => ({ ...ent, [prop]: item[prop] }),
  17. {},
  18. )
  19. : item
  20. if (!actionConfig.indexOn) {
  21. return {
  22. detail: sortedInputs.map(buildEntry),
  23. ref: actionConfig.name,
  24. }
  25. }
  26. const groupOrder = []
  27. const groupSeen = new Set()
  28. for (const item of inputs) {
  29. const items = item?.[actionConfig.indexOn]
  30. const normalizedItems = Array.isArray(items)
  31. ? items
  32. : (items == null ? [] : [items])
  33. for (const value of normalizedItems) {
  34. if (!groupSeen.has(value)) {
  35. groupSeen.add(value)
  36. groupOrder.push(value)
  37. }
  38. }
  39. }
  40. const groups = new Map(groupOrder.map(value => [value, []]))
  41. for (const item of sortedInputs) {
  42. const items = item?.[actionConfig.indexOn]
  43. const normalizedItems = Array.isArray(items)
  44. ? items
  45. : (items == null ? [] : [items])
  46. if (normalizedItems.length === 0) continue
  47. const entry = buildEntry(item)
  48. for (const value of normalizedItems) {
  49. if (!groups.has(value)) {
  50. groups.set(value, [])
  51. }
  52. groups.get(value).push(entry)
  53. }
  54. }
  55. const taxonomy = Object.fromEntries(groups)
  56. return {
  57. detail: taxonomy,
  58. ref: actionConfig.name,
  59. }
  60. }