s3Helper.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import _ from "lodash";
  2. export const s3ContentsToTree = (
  3. s3Contents,
  4. props = {},
  5. reducer: (...args: unknown[]) => Record<string, unknown> = () => ({})
  6. ) => {
  7. let __result = [];
  8. let level = { __result, __prefix: "" };
  9. props = Object.assign(
  10. {
  11. key: "key",
  12. label: "label",
  13. children: "children",
  14. },
  15. props
  16. );
  17. s3Contents.forEach((s3Content) => {
  18. s3Content.Key.split("/").reduce((r, label, i, a) => {
  19. if (!r[label]) {
  20. const __prefix = `${r.__prefix ? r.__prefix + "/" : ""}${label}`;
  21. r[label] = { __result: [], __prefix };
  22. r.__result.push({
  23. [props.key]: __prefix,
  24. [props.label]: label,
  25. [props.children]: r[label].__result,
  26. // NOTE 这里要小心覆盖掉props.key props.label props.children
  27. ...reducer(r, label, i, a, s3Content),
  28. });
  29. }
  30. return r[label];
  31. }, level);
  32. });
  33. return __result;
  34. };
  35. export const trimTreeForSideBar = (tree) => {};
  36. type TreeNodeLike = {
  37. label?: string;
  38. children?: TreeNodeLike[];
  39. __path__?: string[];
  40. } & { [K: string]: unknown };
  41. export const getTreeFlatten = <T extends TreeNodeLike>(
  42. treeNode: T,
  43. order: "preorder" | "postorder" = "preorder",
  44. mode: "all" | "leaf" = "leaf",
  45. path: string[] = []
  46. ): (T & TreeNodeLike)[] => {
  47. treeNode.__path__ = [...path, treeNode.label ?? ""];
  48. if (treeNode.children?.length) {
  49. const result = _.flatMap<T, T>(treeNode.children as T[], (node) =>
  50. getTreeFlatten(node, order, mode, treeNode.__path__)
  51. );
  52. if (mode === "all") {
  53. if (order === "preorder") {
  54. result.unshift(treeNode);
  55. } else if (order === "postorder") {
  56. result.push(treeNode);
  57. }
  58. }
  59. return result;
  60. }
  61. return [treeNode];
  62. };