import React, { useCallback, ChangeEvent, useMemo, useState } from 'react' import { gql, useApolloClient } from '@apollo/client' import { useUploaderProps } from './interfaces' import { uploadToS3 } from '../../helpers/S3Uploader' import { normalizeFileName } from '../../helpers/normalizeFileName' import { UploaderInputStyled, UploaderStyled } from './styles' import { Mutation, MutationS3SignUploadArgs, } from '../../modules/gql/generated/types' export const useUploader = ({ onUpload, inputProps, disabled, // title, ...other }: useUploaderProps) => { const client = useApolloClient() const [loading, loadingSetter] = useState(false) const [input, inputRef] = useState(null) const onClick = useCallback(() => { if (input) { input.click() } }, [input]) const onChange = useCallback( (event: ChangeEvent) => { if (loading) { return } loadingSetter(true) const file = event.target.files && event.target.files[0] if (file) { client .mutate, MutationS3SignUploadArgs>({ mutation: gql` mutation s3SignUpload( $objectName: String! $contentType: String! ) { s3SignUpload( objectName: $objectName contentType: $contentType ) { uploadUrl publicUrl } } `, variables: { contentType: file.type, objectName: normalizeFileName(file.name), }, }) .then(async (response) => { /** * Публичный адрес берём только из ответа подписи: адрес из presigned URL * указывает на хост S3 API и анонимно не читается. */ const signed = response.data?.s3SignUpload if (!signed?.uploadUrl || !signed.publicUrl) { throw new Error('Не получена ссылка для загрузки файла') } await uploadToS3(file, signed.uploadUrl) onUpload(signed.publicUrl) }) .catch((error: Error) => { console.error(error) alert(error.message) }) .finally(() => { loadingSetter(false) }) } }, [client, loading, onUpload] ) const uploader = useMemo(() => { return ( <>