This repository has been archived by the owner on Feb 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmetadata-fetcher.js
97 lines (83 loc) · 2.81 KB
/
metadata-fetcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* Copyright (c) 2017 SugarCRM Inc. Licensed by SugarCRM under the Apache 2.0 license.
*/
let _ = require('lodash');
let utils = require('./utils');
let chakram = require('chakram');
const VERSION = 'v10';
let MetadataFetcher = {
/**
* @property {string} currentRequest The current request to
* fetch metadata, if a request is ongoing.
*/
currentRequest: null,
/**
* Returns a promise that resolves to the formatted metadata.
*
* @return {Promise} A promise that resolves to formatted metadata.
*/
fetch() {
// If there is already a request in progress, return that immediately.
if (this.currentRequest) {
return this.currentRequest;
}
let authToken;
let loginOptions = {
username: process.env.THORN_ADMIN_USERNAME,
password: process.env.THORN_ADMIN_PASSWORD,
version: VERSION,
xthorn: 'MetadataFetcher',
};
let self = this;
// Log into server as admin
this.currentRequest = utils.login(loginOptions)
.then((response) => {
authToken = response.body.access_token;
let url = `${utils.constructUrl(VERSION, 'metadata')}?modules`;
let metadataOptions = {
headers: {
'X-Thorn': 'MetadataFetcher',
'OAuth-Token': authToken,
},
};
// Make request for metadata
return chakram.get(url, metadataOptions);
}).then((response) => {
// Format the metadata
let metadata = {};
let responseJson = response.body;
_.each(responseJson.modules, (data, module) => {
metadata[module] = self._filterByRequiredFields(data.fields);
});
self.currentRequest = null;
return metadata;
});
return this.currentRequest;
},
/**
* Given an object containing the metadata fields,
* returns the fields that are required.
*
* @param {Object} fields The fields to search
*
* @return {Object} The required fields
*
* @private
*/
_filterByRequiredFields(fields) {
let filteredFields = {fields: {}};
_.each(fields, (field, fieldName) => {
if (
!_.isUndefined(field.required) &&
field.required &&
_.isUndefined(field.source) &&
_.isUndefined(field.readonly) &&
(_.isUndefined(field.type) || field.type !== 'id')
) {
filteredFields.fields[fieldName] = field;
}
});
return filteredFields;
},
};
module.exports = MetadataFetcher;