File tree 2 files changed +20
-13
lines changed
2 files changed +20
-13
lines changed Original file line number Diff line number Diff line change
1
+ import { getNextUrl } from '../client/linkHeader' ;
1
2
import { Gateway } from './Gateway' ;
2
3
import * as options from './options' ;
3
4
@@ -20,26 +21,22 @@ export class Qiita extends Gateway {
20
21
/**
21
22
* Qiita APIのページネーションをラップする非同期反復可能オブジェクトを返します
22
23
* nextの引数に文字列 'reset' を渡すと最初のインデックスに戻ることができます。
23
- * @param url リクエストするURL
24
- * @param options リクエストのオプション
24
+ * @param initialUrl 最初にリクエストするURL
25
+ * @param params リクエストのオプション
25
26
*/
26
- public async * paginationGenerator < T extends any [ ] > ( url : string , options ?: any ) {
27
+ public async * paginationGenerator < T extends any [ ] > ( initialUrl : string , params ?: options . PaginationOptions ) {
27
28
// Qiitaのページネーションインデックスは1から始まります
28
- let page = 1 ;
29
+ let next : string | null = initialUrl ;
29
30
30
31
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 ;
33
34
34
35
if ( result === 'reset' ) {
35
- page = 1 ;
36
+ next = initialUrl ;
36
37
} else {
37
- page ++ ;
38
-
39
- // レスポンスの配列の長さがない場合にイテレーターを終了します。
40
- if ( ! data . length ) {
41
- break ;
42
- }
38
+ next = getNextUrl ( response . headers ) ;
39
+ if ( ! next ) { break ; }
43
40
}
44
41
}
45
42
}
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments