-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapi.js
More file actions
85 lines (77 loc) · 2.74 KB
/
api.js
File metadata and controls
85 lines (77 loc) · 2.74 KB
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
/*
* Your installation or use of this SugarCRM file is subject to the applicable
* terms available at
* http://support.sugarcrm.com/Resources/Master_Subscription_Agreements/.
* If you do not agree to all of the applicable terms or do not have the
* authority to bind the entity as an authorized representative, then do not
* install or use this SugarCRM file.
*
* Copyright (C) SugarCRM Inc. All rights reserved.
*/
const axios = require('axios');
const { HttpStatus } = require('../constants/http-status.js');
const loggerUtils = require('../utils/logger-utils');
const { Secrets } = require('../utils/aws/secrets');
const methodToRequest = {
'read': 'GET',
'update': 'PUT',
'create': 'POST',
'delete': 'DELETE'
};
module.exports = () => {
const serverUrl = (process.env.sugarUrl || 'localhost') + '/rest/v11_10';
return {
serverUrl: serverUrl,
buildUrl: function(path) {
return `${serverUrl}/${path}`;
},
call: async function(method, url, data, params) {
const secrets = JSON.parse(await Secrets);
const username = secrets.sugarUsername || '';
const password = secrets.sugarPass || '';
try {
let response = await axios.post(this.buildUrl('oauth2/token'), {
grant_type: 'password',
client_id: 'sugar',
client_secret: '',
username: username,
password: password,
platform: ''
});
if (!(response && response.data && response.data.access_token)) {
return {
status: HttpStatus.authFailure
};
}
let request = {
method: methodToRequest[method],
url: url,
headers: { Authorization: `Bearer ${response.data.access_token}` }
};
if (data) {
request.data = data;
}
if (params) {
request.params = params;
}
response = await axios(request);
if (response.data) {
loggerUtils.logSugarApiResponse(response.data);
return {
status: HttpStatus.ok,
data: response.data
};
} else {
return {
status: HttpStatus.notFound
};
}
} catch (error) {
return {
status: HttpStatus.error,
error: error
};
}
}
};
};