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

49 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-11-29 20:05:48 +00:00
const { getAccessToken } = require('./oauth2')
async function requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '') {
let config = {}
url = url.replace('crmPhone', crmPhone)
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}`,
}
}
}
return config
}
module.exports = requestConfigHeader