попытка сделать нормальный интерцептор
This commit is contained in:
@@ -3,37 +3,73 @@ import { Api } from '~/api/Api'
|
||||
const requestUrl = 'https://wp.koptilnya.xyz/wp-json'
|
||||
const consumerKey = 'ck_8b5477a1573ce6038ef1367f25d95cede1de4559'
|
||||
const consumerSecret = 'cs_d0ccaa93e8efe4f76eef0b70c9828a58fc53459f'
|
||||
|
||||
const authString = `${consumerKey}:${consumerSecret}`
|
||||
const encodedAuth = btoa(unescape(encodeURIComponent(authString)))
|
||||
|
||||
// Создаем инстанс API
|
||||
const api = new Api({
|
||||
baseUrl: String(requestUrl),
|
||||
})
|
||||
|
||||
Object.keys(api.wc).forEach((methodName) => {
|
||||
const nativeMethod = api.wc[methodName] as typeof Function
|
||||
const argsNumber = nativeMethod.length
|
||||
api.wc[methodName] = function (...args) {
|
||||
let params: Record<string, unknown> = {}
|
||||
if (args.length > argsNumber) {
|
||||
params = args.pop()
|
||||
}
|
||||
|
||||
return nativeMethod(...args, {
|
||||
...params,
|
||||
baseUrl: requestUrl,
|
||||
securityWorker: (securityData) => {
|
||||
return {
|
||||
headers: {
|
||||
...(params.headers as Record<string, string> ?? {}),
|
||||
Authorization: `Basic ${encodedAuth}`,
|
||||
'Authorization': `Basic ${encodedAuth}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
} as unknown as string)
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
// Модифицируем методы API для автоматической аутентификации
|
||||
Object.keys(api.wc).forEach((namespace) => {
|
||||
const namespaceObj = api.wc[namespace]
|
||||
|
||||
Object.keys(namespaceObj).forEach((methodName) => {
|
||||
const originalMethod = namespaceObj[methodName]
|
||||
|
||||
namespaceObj[methodName] = async function (...args: any[]) {
|
||||
try {
|
||||
// Добавляем заголовки аутентификации
|
||||
const lastArg = args[args.length - 1]
|
||||
const options = typeof lastArg === 'object' ? lastArg : {}
|
||||
|
||||
const modifiedOptions = {
|
||||
...options,
|
||||
headers: {
|
||||
...(options.headers || {}),
|
||||
Authorization: `Basic ${encodedAuth}`,
|
||||
},
|
||||
}
|
||||
|
||||
// Заменяем последний аргумент на модифицированные опции
|
||||
const modifiedArgs = typeof lastArg === 'object'
|
||||
? [...args.slice(0, -1), modifiedOptions]
|
||||
: [...args, modifiedOptions]
|
||||
|
||||
const response = await originalMethod.apply(this, modifiedArgs)
|
||||
return response.json()
|
||||
}
|
||||
catch (error) {
|
||||
console.error(`API Error in ${namespace}.${methodName}:`, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// Переопределяем базовый request для обработки ошибок
|
||||
const nativeRequest = api.request
|
||||
|
||||
api.request = async function (...args) {
|
||||
const response = await nativeRequest.call(api, ...args)
|
||||
return await response.json()
|
||||
try {
|
||||
const response = await nativeRequest.call(api, ...args)
|
||||
console.log('response', response.json())
|
||||
return response.data
|
||||
}
|
||||
catch (error) {
|
||||
console.error('API Request Error:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export default api
|
||||
|
||||
Reference in New Issue
Block a user