Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add .meta and .includes access for v2 paginators #46

Merged
merged 1 commit into from
Jul 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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