/ libs / utils / src / featured.ts
featured.ts
 1  import { Tree } from '@hatsprotocol/sdk-v1-subgraph';
 2  import { FEATURED_TREES } from '@hatsprotocol/config';
 3  import _ from 'lodash';
 4  import { prettyIdToIp } from 'shared';
 5  import { AppHat } from 'types';
 6  
 7  import { removeInactiveHatsAndDescendants } from './hats';
 8  import { ipfsUrl } from './image';
 9  import { fetchTreeDetailsMesh, fetchTreesByIdMesh } from './subgraph';
10  
11  export const fetchFeaturedTreesData = async ({ featuredTrees }: { featuredTrees: any[] }) => {
12    const chainIds = _.uniq(_.map(featuredTrees, 'chainId'));
13  
14    const promises = _.map(chainIds, (chainId: number) => {
15      const trees = _.filter(featuredTrees, { chainId });
16      if (_.size(trees) > 1) {
17        return fetchTreesByIdMesh(_.map(trees, 'id'), chainId);
18      }
19  
20      // TODO combine using id_in
21      return fetchTreeDetailsMesh(_.first(trees).id, chainId);
22    });
23  
24    const result = await Promise.all(_.flatten(promises));
25  
26    const data = _.map(_.flatten(result), (tree: Tree) => {
27      const onlyActiveHats = removeInactiveHatsAndDescendants(tree.hats);
28      return {
29        treeId: prettyIdToIp(tree.id),
30        hats: _.size(onlyActiveHats),
31        // try to get unique wearers across active hats
32        // TODO doesn't account well for hats with many (100+) wearers
33        wearers: _.size(_.uniq(_.flatten(_.map(onlyActiveHats, (hat: AppHat) => hat.wearers)))),
34      };
35    });
36  
37    return data;
38  };
39  
40  export const fetchFeaturedTrees = () => FEATURED_TREES({ ipfsUrl });