masto
Version:
Mastodon API client for JavaScript, TypeScript, Node.js, browsers
59 lines (58 loc) • 1.69 kB
JavaScript
import { parseLinkHeader } from "../../utils/index.js";
export class PaginatorHttp {
http;
raw;
path;
params;
meta;
direction;
constructor(http, raw, path, params, meta, direction = "next") {
this.http = http;
this.raw = raw;
this.path = path;
this.params = params;
this.meta = meta;
this.direction = direction;
}
async *values() {
let path = this.path;
let params = this.params;
while (path != undefined) {
const response = await this.http.request({
method: "GET",
path,
search: params,
...this.meta,
});
const nextUrl = this.getLink(response.headers.get("link"));
path = nextUrl?.pathname;
params = nextUrl?.search.replace(/^\?/, "");
const data = (this.raw ? response : response.data);
yield data;
}
}
then(onfulfilled = Promise.resolve.bind(Promise), onrejected = Promise.reject.bind(Promise)) {
return this.values()
.next()
.then((value) => onfulfilled(value.value), onrejected);
}
getDirection() {
return this.direction;
}
setDirection(direction) {
return new PaginatorHttp(this.http, this.raw, this.path, this.params, this.meta, direction);
}
[Symbol.asyncIterator]() {
return this.values();
}
getLink(value) {
if (!value) {
return;
}
const parsed = parseLinkHeader(value).get(this.direction);
if (!parsed) {
return;
}
return new URL(parsed);
}
}