UNPKG

1.77 kBJavaScriptView Raw
1'use strict';
2
3const signedFetch = require('signed-aws-es-fetch');
4const logger = require('@financial-times/n-logger').default;
5
6function compat (tag) {
7 return {
8 term: {
9 name: tag.prefLabel,
10 attributes: tag.attributes,
11 id: tag.idV1,
12 taxonomy: tag.taxonomy
13 }
14 };
15}
16
17function getTag (id, type) {
18 const data = {
19 _source:['metadata'],
20 query: {
21 term: {}
22 },
23 sort: {
24 publishedDate: {
25 order: 'desc'
26 }
27 },
28 size: 1
29 };
30 data.query.term[`metadata.${type}`] = id;
31
32 return signedFetch('https://next-elastic.ft.com/v3_api_v2/item/_search', {
33 method: 'POST',
34 timeout: 3000,
35 headers: {
36 'Content-Type': 'application/json'
37 },
38 body: JSON.stringify(data)
39 })
40 .then(res => {
41 if (res.ok) {
42 return res.json();
43 }
44 throw new Error('Can\'t find tag');
45 })
46 .then(data => {
47 if (data.hits.hits[0]) {
48 return {
49 status: 200,
50 body: compat(data.hits.hits[0]._source.metadata.find(tag => tag[type] === id))
51 };
52 }
53 return {
54 status: 404,
55 body: { error: 'Not found, could be deleted or might never had existed' }
56 };
57 })
58 .catch(() => {
59 return {
60 status: 500,
61 body: { error: 'Server error' }
62 };
63 });
64}
65
66module.exports = (opts) => {
67 const identifierValues = opts.identifierValues;
68 const identifierType = opts.identifierType || 'idV1';
69
70 if(identifierValues.length === 0 || !Array.isArray(identifierValues)) {
71 return Promise.resolve([]);
72 }
73
74 return Promise.all(
75 identifierValues.map(id => getTag(id, identifierType))
76 ).then(results => {
77 const items = results
78 .filter(r => r.status === 200)
79 .map(r => r.body.term);
80 return {
81 total: items.length,
82 items
83 };
84 })
85 .catch((err) => {
86 logger.warn('Failed getting ElasticSearch things', {
87 identifierValues,
88 error: err
89 });
90 });
91};