UNPKG

1.75 kBJavaScriptView Raw
1import URL from 'url';
2import OBJ from 'dot-prop';
3import fetch from 'fetch-with-proxy';
4import QueryString from 'qs';
5import { newValue } from './utils';
6
7/**
8 * Take `Object` with `id` and returns the document's metadata
9 *
10 * @param {string} [source="id"] Field to use to fetch documents
11 * @param {string} target
12 * @param {string} [id=data.id] ISTEX Identifier of a document
13 * @param {string} [sid="ezs-istex"] User-agent identifier
14 * @returns {Array<Object>}
15 */
16function 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
59export default {
60 ISTEXFetch,
61};