| 1 |
import { useMemo } from 'react' |
| 2 |
import { useAxios } from './useAxios' |
| 3 |
import type { AxiosResponse, CreateAxiosDefaults } from 'axios' |
| 4 |
|
| 5 |
export interface FileUploadRequest { |
| 6 |
files: FileList |
| 7 |
} |
| 8 |
|
| 9 |
export interface FileParseResponse { |
| 10 |
snippets: ImportableSnippet[] |
| 11 |
total_count: number |
| 12 |
message: string |
| 13 |
warnings?: string[] |
| 14 |
} |
| 15 |
|
| 16 |
export interface ImportableSnippet { |
| 17 |
id?: number |
| 18 |
name: string |
| 19 |
desc?: string |
| 20 |
description?: string |
| 21 |
code: string |
| 22 |
tags?: string[] |
| 23 |
scope?: string |
| 24 |
source_file?: string |
| 25 |
table_data: { |
| 26 |
id: number | string |
| 27 |
title: string |
| 28 |
scope: string |
| 29 |
tags: string |
| 30 |
description: string |
| 31 |
type: string |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
export interface SnippetImportRequest { |
| 36 |
snippets: ImportableSnippet[] |
| 37 |
duplicate_action: 'ignore' | 'replace' | 'skip' |
| 38 |
network?: boolean |
| 39 |
} |
| 40 |
|
| 41 |
export interface SnippetImportResponse { |
| 42 |
imported: number |
| 43 |
imported_ids: number[] |
| 44 |
message: string |
| 45 |
} |
| 46 |
|
| 47 |
const ROUTE_BASE = `${window.CODE_SNIPPETS?.restAPI.base}code-snippets/v1/` |
| 48 |
|
| 49 |
const AXIOS_CONFIG: CreateAxiosDefaults = { |
| 50 |
headers: { 'X-WP-Nonce': window.CODE_SNIPPETS?.restAPI.nonce } |
| 51 |
} |
| 52 |
|
| 53 |
export interface FileUploadAPI { |
| 54 |
parseFiles: (request: FileUploadRequest) => Promise<AxiosResponse<FileParseResponse>> |
| 55 |
importSnippets: (request: SnippetImportRequest) => Promise<AxiosResponse<SnippetImportResponse>> |
| 56 |
} |
| 57 |
|
| 58 |
export const useFileUploadAPI = (): FileUploadAPI => { |
| 59 |
const { axiosInstance } = useAxios(AXIOS_CONFIG) |
| 60 |
|
| 61 |
return useMemo((): FileUploadAPI => ({ |
| 62 |
parseFiles: (request: FileUploadRequest) => { |
| 63 |
const formData = new FormData() |
| 64 |
|
| 65 |
for (let i = 0; i < request.files.length; i++) { |
| 66 |
formData.append('files[]', request.files[i]) |
| 67 |
} |
| 68 |
|
| 69 |
return axiosInstance.post<FileParseResponse>( |
| 70 |
`${ROUTE_BASE}file-upload/parse`, |
| 71 |
formData, |
| 72 |
{ |
| 73 |
headers: { |
| 74 |
'Content-Type': 'multipart/form-data', |
| 75 |
} |
| 76 |
} |
| 77 |
) |
| 78 |
}, |
| 79 |
|
| 80 |
importSnippets: (request: SnippetImportRequest) => { |
| 81 |
return axiosInstance.post<SnippetImportResponse>( |
| 82 |
`${ROUTE_BASE}file-upload/import`, |
| 83 |
request |
| 84 |
) |
| 85 |
} |
| 86 |
}), [axiosInstance]) |
| 87 |
} |
| 88 |
|