76 lines
2.3 KiB
TypeScript
76 lines
2.3 KiB
TypeScript
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: requestUrl,
|
|
securityWorker: (securityData) => {
|
|
return {
|
|
headers: {
|
|
'Authorization': `Basic ${encodedAuth}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
}
|
|
},
|
|
})
|
|
|
|
// Модифицируем методы 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) {
|
|
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
|