Como que tá...

mail@pastecode.io avatar
unknown
typescript
2 years ago
1.6 kB
2
Indexable
Never
import axios from 'axios';
import fp from 'fastify-plugin'

interface Item {
  id: string,
  absoluteIndex: number,
  name: string
}

interface PageMetaData {
  dataPerRequest: number,
  startIndex: number,
  externalPage: number,
  endIndex: number,
  items: Item[]
}

function buildPageMetadata(page, perPage): PageMetaData {
  let dataPerRequest = perPage / 100;
  let startIndex = ((page - 1) * perPage) % 100
  return {
    dataPerRequest,
    startIndex,
    externalPage: Math.floor(dataPerRequest * (page - 1) + 1),
    endIndex: startIndex + perPage,
    items: []
  }
}

function nextPage(pageMetaData: PageMetaData) {
  return {
    ...pageMetaData,
    externalPage: pageMetaData.externalPage++,
    startIndex: 0,
    endIndex: pageMetaData.dataPerRequest - pageMetaData.items.length
  }
}

async function fetchExternalPage(externalPage: number) {
  return await axios.get(`http://sf-legacy-api.now.sh/items?page=${externalPage}`);
}

async function fetchItemsData(page: number, perPage: number) {
  let pageMetadata = buildPageMetadata(page, perPage);

  while (perPage > pageMetadata.items.length) {
    const { data: { data: legacyItems } } = await fetchExternalPage(pageMetadata.externalPage);
    const tempItems = legacyItems.slice(pageMetadata.startIndex, pageMetadata.endIndex);
    pageMetadata.items = [...pageMetadata.items, ...tempItems]
    pageMetadata = nextPage(pageMetadata);
  };

  return pageMetadata.items;
}

export default fp(async (fastify) => {
  fastify.decorate('fetchItemsData', fetchItemsData);
})

declare module 'fastify' {
  export interface FastifyInstance {
    fetchItemsData(): Item[];
  }
}