Skip to content

Commit ee08cbe

Browse files
committed
ページネーションにlink headerを利用
1 parent 22ed986 commit ee08cbe

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

src/client/Qiita.ts

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { getNextUrl } from '../client/linkHeader';
12
import { Gateway } from './Gateway';
23
import * as options from './options';
34

@@ -20,26 +21,22 @@ export class Qiita extends Gateway {
2021
/**
2122
* Qiita APIのページネーションをラップする非同期反復可能オブジェクトを返します
2223
* nextの引数に文字列 'reset' を渡すと最初のインデックスに戻ることができます。
23-
* @param url リクエストするURL
24-
* @param options リクエストのオプション
24+
* @param initialUrl 最初にリクエストするURL
25+
* @param params リクエストのオプション
2526
*/
26-
public async * paginationGenerator <T extends any[]> (url: string, options?: any) {
27+
public async * paginationGenerator <T extends any[]> (initialUrl: string, params?: options.PaginationOptions) {
2728
// Qiitaのページネーションインデックスは1から始まります
28-
let page = 1;
29+
let next: string|null = initialUrl;
2930

3031
while (true) {
31-
const data = await this.get<T>(url, { ...options, page });
32-
const result: T | 'reset' = yield data;
32+
const response = await this.get<T>(next, { ...params });
33+
const result: T | 'reset' = yield response;
3334

3435
if (result === 'reset') {
35-
page = 1;
36+
next = initialUrl;
3637
} else {
37-
page++;
38-
39-
// レスポンスの配列の長さがない場合にイテレーターを終了します。
40-
if (!data.length) {
41-
break;
42-
}
38+
next = getNextUrl(response.headers);
39+
if (!next) { break; }
4340
}
4441
}
4542
}

src/client/linkHeader.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import * as LinkHeader from 'http-link-header';
2+
3+
export const getNextUrl = (headers: Headers): string | null => {
4+
const link = headers.get('Link') || '';
5+
const refs = LinkHeader.parse(link).refs.filter((ref) => ref.rel === 'next');
6+
7+
return refs.length > 0
8+
? refs[0].uri
9+
: null;
10+
};

0 commit comments

Comments
 (0)