crm-api-template-generator/backend/utils/requestConfigHeader.js

69 lines
1.9 KiB
JavaScript

const { getAccessToken } = require('./oauth2')
async function requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '') {
let config = {}
console.log('requestConfigHeader ticketId: ', ticketId)
url = url.replace('crmPhone', crmPhone)
url = url.replace('ticketId', ticketId)
if (type == 'api_token') {
if (requestType.trim().toLowerCase() == 'post') {
url = `${url}?api_token=${token}`
}
else if (requestType.trim().toLowerCase() == 'get') {
url = `${url}&api_token=${token}`
}
}
let commonConfig = {
method: requestType,
url,
headers: {
'Content-Type': requestContentType,
}
}
if (data) {
commonConfig = { ...commonConfig, data }
}
if (type === 'basic') {
const auth = Buffer.from(`${userName}:${passWord}`).toString('base64')
config = {
...commonConfig,
headers: {
...commonConfig.headers,
'Authorization': `Basic ${auth}`,
}
}
} else if (type === 'bearer') {
config = {
...commonConfig,
headers: {
...commonConfig.headers,
'Authorization': `Bearer ${token}`,
}
}
} else if (type === 'oauth2') {
const accessToken = await getAccessToken(crmClientId)
config = {
...commonConfig,
headers: {
...commonConfig.headers,
'Authorization': `Bearer ${accessToken}`,
}
}
}
else if (type === 'api_token') {
config = {
...commonConfig,
headers: {
...commonConfig.headers,
}
}
}
return config
}
module.exports = requestConfigHeader