Agora ta assim ohh

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

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

interface PageMetadata {
  perPage: number,
  page: number,
  dataPerRequest: number,
  startIndex: number,
  externalPage: number,
  endIndex: number,
  items: Item[]
}

const paginate = () => {
  function buildPageMetadata(page: number, perPage: number): PageMetadata {
    // Number of fetched data pe
    let dataPerRequest = perPage / 100;
    let startIndex = ((page - 1) * perPage) % 100;

    return {
      perPage,
      page,
      dataPerRequest,
      startIndex,
      externalPage: Math.floor(dataPerRequest * (page - 1) + 1),
      endIndex: startIndex + perPage,
      items: []
    }
  }
  
  function nextPage(pageMetadata: PageMetadata) {
    return {
      ...pageMetadata,
      externalPage: pageMetadata.externalPage + 1,
      startIndex: 0,
      endIndex: pageMetadata.perPage - pageMetadata.items.length
    }
  }
  
  async function fetchExternalPage(externalPage: number) {
    return await axios.get(`http://sf-legacy-api.now.sh/items?page=${externalPage}`);
  }

  async function buildPage(metadata: PageMetadata): Promise<Item[]> {  
    let pageMetadata = metadata;
    while (pageMetadata.perPage > pageMetadata.items.length) {
      const { data: { data: items } } = await fetchExternalPage(pageMetadata.externalPage);
      const tempItems = items.slice(pageMetadata.startIndex, pageMetadata.endIndex);
      pageMetadata.items = [...pageMetadata.items, ...tempItems]
      pageMetadata = nextPage(pageMetadata);
    };
    return pageMetadata.items;
  }

  return {
    buildPage,
    buildPageMetadata
  }
}

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

declare module 'fastify' {
  export interface FastifyInstance {
    paginate(): {(pageMetadata: PageMetadata): Item[], (page: number, perPage: number): PageMetadata};
  }
}