1 | 'use strict';
|
2 |
|
3 | const fetchres = require('fetchres');
|
4 | const logger = require('@financial-times/n-logger').default;
|
5 | const elasticAgent = require('./utils/elastic-agent');
|
6 | const signedFetch = require('signed-aws-es-fetch');
|
7 |
|
8 | module.exports = function (opts) {
|
9 | const uuid = [].concat(opts.uuid);
|
10 | const returnMany = Array.isArray(opts.uuid);
|
11 | const source = 'source' in opts ? opts.source : true;
|
12 | const agent = 'agent' in opts ? opts.agent : elasticAgent;
|
13 |
|
14 | if (uuid.length === 0) {
|
15 | return Promise.resolve([]);
|
16 | }
|
17 |
|
18 | const query = {
|
19 | docs: uuid.map(function (uuid) {
|
20 | return { _id: uuid, _source: source };
|
21 | })
|
22 | };
|
23 |
|
24 | return signedFetch('https://next-elastic.ft.com/v3_api_v2/item/_mget', {
|
25 | method: 'POST',
|
26 | body: JSON.stringify(query),
|
27 | timeout: 3000,
|
28 | agent
|
29 | })
|
30 | .then(function (response) {
|
31 | if (!response.ok) {
|
32 | logger.warn('Failed getting ElasticSearch content', {
|
33 | uuid: uuid,
|
34 | status: response.status
|
35 | });
|
36 | }
|
37 | return response;
|
38 | })
|
39 | .then(fetchres.json)
|
40 | .then(function (data) {
|
41 | let foundCount = 0;
|
42 | const docs = data.docs
|
43 |
|
44 |
|
45 | .filter(function (item) {
|
46 | if (item.found) {
|
47 | foundCount++;
|
48 | return true;
|
49 | }
|
50 | })
|
51 | .map(function (item) {
|
52 | return item._source;
|
53 | });
|
54 | if (returnMany) {
|
55 | return docs;
|
56 | }
|
57 | if (foundCount === 0) {
|
58 | throw new fetchres.BadServerResponseError(404);
|
59 | }
|
60 | return docs[0];
|
61 | });
|
62 | };
|