попытка сделать нормальный интерцептор
This commit is contained in:
parent
34da06301b
commit
51137c6694
11252
api/Api.ts
11252
api/Api.ts
File diff suppressed because it is too large
Load Diff
@ -1,4 +0,0 @@
|
|||||||
import api from '~/api/instance'
|
|
||||||
|
|
||||||
export const getProductList = () =>
|
|
||||||
api.wc.v3ProductsList()
|
|
||||||
8
api/endpoints/getProductsDetail.ts
Normal file
8
api/endpoints/getProductsDetail.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import api from '~/api/instance'
|
||||||
|
|
||||||
|
export const getProductsDetail = (productId: number) =>
|
||||||
|
api.wc.v1ProductsDetail(productId)
|
||||||
|
.then(({ data }) => {
|
||||||
|
console.log('data', data)
|
||||||
|
return data
|
||||||
|
})
|
||||||
@ -1 +1 @@
|
|||||||
export * from './getProductList'
|
export * from './getProductsDetail'
|
||||||
|
|||||||
@ -3,37 +3,73 @@ import { Api } from '~/api/Api'
|
|||||||
const requestUrl = 'https://wp.koptilnya.xyz/wp-json'
|
const requestUrl = 'https://wp.koptilnya.xyz/wp-json'
|
||||||
const consumerKey = 'ck_8b5477a1573ce6038ef1367f25d95cede1de4559'
|
const consumerKey = 'ck_8b5477a1573ce6038ef1367f25d95cede1de4559'
|
||||||
const consumerSecret = 'cs_d0ccaa93e8efe4f76eef0b70c9828a58fc53459f'
|
const consumerSecret = 'cs_d0ccaa93e8efe4f76eef0b70c9828a58fc53459f'
|
||||||
|
|
||||||
const authString = `${consumerKey}:${consumerSecret}`
|
const authString = `${consumerKey}:${consumerSecret}`
|
||||||
const encodedAuth = btoa(unescape(encodeURIComponent(authString)))
|
const encodedAuth = btoa(unescape(encodeURIComponent(authString)))
|
||||||
|
|
||||||
|
// Создаем инстанс API
|
||||||
const api = new Api({
|
const api = new Api({
|
||||||
baseUrl: String(requestUrl),
|
baseUrl: requestUrl,
|
||||||
|
securityWorker: (securityData) => {
|
||||||
|
return {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Basic ${encodedAuth}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
Object.keys(api.wc).forEach((methodName) => {
|
// Модифицируем методы API для автоматической аутентификации
|
||||||
const nativeMethod = api.wc[methodName] as typeof Function
|
Object.keys(api.wc).forEach((namespace) => {
|
||||||
const argsNumber = nativeMethod.length
|
const namespaceObj = api.wc[namespace]
|
||||||
api.wc[methodName] = function (...args) {
|
|
||||||
let params: Record<string, unknown> = {}
|
|
||||||
if (args.length > argsNumber) {
|
|
||||||
params = args.pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nativeMethod(...args, {
|
Object.keys(namespaceObj).forEach((methodName) => {
|
||||||
...params,
|
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: {
|
headers: {
|
||||||
...(params.headers as Record<string, string> ?? {}),
|
...(options.headers || {}),
|
||||||
Authorization: `Basic ${encodedAuth}`,
|
Authorization: `Basic ${encodedAuth}`,
|
||||||
},
|
},
|
||||||
} as unknown as string)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Заменяем последний аргумент на модифицированные опции
|
||||||
|
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
|
const nativeRequest = api.request
|
||||||
|
|
||||||
api.request = async function (...args) {
|
api.request = async function (...args) {
|
||||||
|
try {
|
||||||
const response = await nativeRequest.call(api, ...args)
|
const response = await nativeRequest.call(api, ...args)
|
||||||
return await response.json()
|
console.log('response', response.json())
|
||||||
|
return response.data
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.error('API Request Error:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default api
|
export default api
|
||||||
|
|||||||
@ -1 +1 @@
|
|||||||
export * from './useGetProductList'
|
export * from './useGetProductsDetail'
|
||||||
|
|||||||
@ -1,9 +0,0 @@
|
|||||||
import { useQuery } from '@tanstack/vue-query'
|
|
||||||
import { getProductList } from '~/api/endpoints'
|
|
||||||
|
|
||||||
export const useGetProductList = () => {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ['get-product-list'],
|
|
||||||
queryFn: () => getProductList(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
14
api/queries/useGetProductsDetail.ts
Normal file
14
api/queries/useGetProductsDetail.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { useQuery } from '@tanstack/vue-query'
|
||||||
|
import { unref, watch } from 'vue'
|
||||||
|
import { getProductsDetail } from '~/api/endpoints'
|
||||||
|
|
||||||
|
export const useGetProductsDetail = (productId: MaybeRef<number>) => {
|
||||||
|
const q = useQuery({
|
||||||
|
queryKey: ['get-products-detail', unref(productId)],
|
||||||
|
queryFn: () => getProductsDetail(unref(productId)),
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(() => productId, () => q.refetch())
|
||||||
|
|
||||||
|
return q
|
||||||
|
}
|
||||||
@ -1,14 +0,0 @@
|
|||||||
import { useAsyncData } from '#app'
|
|
||||||
|
|
||||||
export function useGetProducts() {
|
|
||||||
return useAsyncData(
|
|
||||||
'products',
|
|
||||||
async () => {
|
|
||||||
const response = await $fetch('https://wp.koptilnya.xyz/wp-json/wp/v2/product')
|
|
||||||
return response
|
|
||||||
},
|
|
||||||
{
|
|
||||||
server: false,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@ -8,7 +8,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useGetProductList } from '~/api/queries'
|
import { useGetProductsDetail } from '~/api/queries'
|
||||||
|
|
||||||
const { data: productsData } = useGetProductList()
|
const { data: productsData } = useGetProductsDetail(79)
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user