const axios = require('axios');
const CryptoJS = require('crypto-js');
const ACCOUNT_ID = '';
const ENDPOINT = ``;
const AUTH = {
consumerKey: '',
consumerSecret: '',
token: '',
tokenSecret: ''
};
function generateOAuthHeader(httpMethod, url) {
try {
const nonce = Math.random().toString(36).substring(2);
const timestamp = Math.floor(Date.now() / 1000).toString();
const signatureMethod = 'HMAC-SHA256';
const version = '1.0';
const oauthParams = {
oauth_consumer_key: AUTH.consumerKey,
oauth_token: AUTH.token,
oauth_signature_method: signatureMethod,
oauth_timestamp: timestamp,
oauth_nonce: nonce,
oauth_version: version
};
const urlParts = url.split('?');
const baseUrl = urlParts[0];
const queryParams = urlParts[1]
? Object.fromEntries(urlParts[1].split('&').map(param => {
const [key, value] = param.split('=');
return [decodeURIComponent(key), decodeURIComponent(value)];
}))
: {};
const allParams = { ...oauthParams, ...queryParams };
const sortedParamString = Object.keys(allParams)
.sort()
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(allParams[key])}`)
.join('&');
const baseString = [
httpMethod.toUpperCase(),
encodeURIComponent(baseUrl),
encodeURIComponent(sortedParamString)
].join('&');
const signingKey = `${encodeURIComponent(AUTH.consumerSecret)}&${encodeURIComponent(AUTH.tokenSecret)}`;
const rawSignature = CryptoJS.HmacSHA256(baseString, signingKey);
const signature = CryptoJS.enc.Base64.stringify(rawSignature);
oauthParams.oauth_signature = signature;
const authHeader = 'OAuth realm="' + ACCOUNT_ID + '", ' + Object.keys(oauthParams)
.map(key => `${encodeURIComponent(key)}="${encodeURIComponent(oauthParams[key])}"`)
.join(', ');
console.log("authHeader", authHeader);
return authHeader;
} catch (e) {
log.error('Error @ generateOAuthHeader', e.message);
throw e;
}
}
async function sendViaRestAPI(payload) {
try {
const url = ENDPOINT
const response = await axios.post(url, payload, {
headers: {
'Authorization': generateOAuthHeader("POST", url),
'Content-Type': 'application/json',
'Accept': 'application/vnd.oracle.resource+json; type=singular'
}
});
return response.data;
} catch (error) {
console.error('Error @ sendViaRestAPI', error.message);
throw error;
}
}
(async () => {
const payload = {} //Payload
try {
const result = await sendViaRestAPI(payload);
console.log("API Response:" , result?.data.length);
} catch (err) {
console.error("API Call Failed:", err);
}
})();