1 | import URL from 'url';
|
2 | import OBJ from 'dot-prop';
|
3 | import fetch from 'fetch-with-proxy';
|
4 | import QueryString from 'qs';
|
5 | import { newValue } from './utils';
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function ISTEXFetch(data, feed) {
|
17 | if (this.isLast()) {
|
18 | return feed.close();
|
19 | }
|
20 | const source = this.getParam('source', 'id');
|
21 | const target = this.getParam('target');
|
22 | const id = this.getParam('id', OBJ.get(data, source, data));
|
23 | const sid = this.getParam('sid', 'ezs-istex');
|
24 | const location = {
|
25 | protocol: 'https:',
|
26 | host: 'api.istex.fr',
|
27 | };
|
28 | if (id.length === 40) {
|
29 | location.pathname = '/document/'.concat(id);
|
30 | } else if (id.search(/^ark:/) === 0) {
|
31 | location.pathname = String(id).concat('/record.json');
|
32 | } else {
|
33 | throw new Error('Unexpected id.');
|
34 | }
|
35 | const parameters = {
|
36 | sid,
|
37 | };
|
38 | const urlObj = {
|
39 | ...location,
|
40 | search: QueryString.stringify(parameters),
|
41 | };
|
42 | const urlStr = URL.format(urlObj);
|
43 | fetch(urlStr)
|
44 | .then(response => response.json())
|
45 | .then((json) => {
|
46 | if (json._error) {
|
47 | throw new Error(json._error);
|
48 | }
|
49 | return feed.send(newValue(json, target, data));
|
50 | })
|
51 | .catch((err) => {
|
52 | err.url = urlStr;
|
53 | err.input = data;
|
54 | err.target = target;
|
55 | feed.send(err);
|
56 | });
|
57 | }
|
58 |
|
59 | export default {
|
60 | ISTEXFetch,
|
61 | };
|