Skip to content

Commit

Permalink
Merge pull request #46 from PLhery/feature/paginator-v2-meta-property
Browse files Browse the repository at this point in the history
feat: Add .meta and .includes access for v2 paginators
  • Loading branch information
alkihis authored Jul 29, 2021
2 parents d4cba5e + 6b4a02b commit 98fa773
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
18 changes: 18 additions & 0 deletions doc/paginators.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,24 @@ for await (const tweet of homeTimeline) {
}
```

## v2 meta, includes

For tweets endpoints that returns `meta`s and `includes` in their payload, `v2` paginators supports them (and merge them into a unique container :D),
just use `Paginator.meta` or `Paginator.includes`.

```ts
const mySearch = await client.v2.search('nodeJS');

for await (const tweet of mySearch) {
const availableMeta = mySearch.meta;
const availableIncludes = mySearch.includes;

// availableMeta and availableIncludes are filled with .meta and .includes
// fetched at the time you were reading this tweet
// Once the next page is automatically fetched, they can be updated!
}
```

## Previous page

On paginators that supports it, you can get previous pages with `.previous()` and `.fetchPrevious()`.
Expand Down
33 changes: 33 additions & 0 deletions src/paginators/tweet.paginator.v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
TweetV2TimelineParams,
TweetV2UserTimelineResult,
TweetV2UserTimelineParams,
ApiV2Includes,
} from '../types';

/** A generic PreviousableTwitterPaginator able to consume TweetV2 timelines. */
Expand All @@ -31,6 +32,30 @@ abstract class TweetTimelineV2Paginator<
this._realData.meta.result_count += result.meta.result_count;
this._realData.data.unshift(...result.data);
}

this.updateIncludes(result);
}

protected updateIncludes(data: TResult) {
if (!data.includes) {
return;
}
if (!this._realData.includes) {
this._realData.includes = {};
}

const includesRealData = this._realData.includes;

for (const [includeKey, includeArray] of Object.entries(data.includes) as [keyof ApiV2Includes, any[]][]) {
if (!includesRealData[includeKey]) {
includesRealData[includeKey] = [];
}

includesRealData[includeKey] = [
...includesRealData[includeKey]!,
...includeArray,
];
}
}

protected getNextQueryParams(maxResults?: number) {
Expand Down Expand Up @@ -67,6 +92,14 @@ abstract class TweetTimelineV2Paginator<
get tweets() {
return this._realData.data;
}

get meta() {
return this._realData.meta;
}

get includes() {
return this._realData.includes ?? {};
}
}

// ----------------
Expand Down

0 comments on commit 98fa773

Please sign in to comment.