diff --git a/src/pages/api/verify-file.ts b/src/pages/api/verify-file.ts deleted file mode 100644 index 553bb98..0000000 --- a/src/pages/api/verify-file.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { NextApiRequest, NextApiResponse } from 'next' - - -const verify = async (bytes: Buffer) => { -} - -export default async (req: NextApiRequest, res: NextApiResponse) => { - let body = ''; - let buffer; - req.on('data', (chunk) => { - body += chunk.toString() - }) - req.on('end', () => { - const params = JSON.parse(body) - buffer = Object.values(params.file) - }) - const { status, ...response }: any = await verify(buffer) - -} - -export const config = { - api: { - bodyParser: false - } -} diff --git a/src/pages/error.tsx b/src/pages/error.tsx index 7e37568..304386f 100644 --- a/src/pages/error.tsx +++ b/src/pages/error.tsx @@ -20,7 +20,7 @@ const ErrorPage = () => { return ( <> {line} - {index != phrase.length - 1 &&
} + {index !== phrase.length - 1 &&
} ) }) diff --git a/src/pages/index.tsx b/src/pages/index.tsx index bd38540..759a4ef 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -35,7 +35,7 @@ const FileVerification: NextPage<{}> = () => { try { const { error, message, hash, url, timestamp }: any = await ApiClient.verifyFile(uploadedFile) - if (message == 'OK') { + if (message === 'OK') { router.push(`/success?timestamp=${timestamp}&url=${url}&hash=${hash}`, '/success') } else { router.push('/error?error=' + error) diff --git a/src/pages/validateQR/index.tsx b/src/pages/validateQR/index.tsx index d32142b..8e3257d 100644 --- a/src/pages/validateQR/index.tsx +++ b/src/pages/validateQR/index.tsx @@ -1,67 +1,64 @@ /* eslint-disable camelcase */ -import React, { useEffect, useState } from 'react' -import { NextPage } from 'next' -import { useRouter } from 'next/router' -import { Button, Upload, Layout, Col, Row } from 'antd' -import { UploadOutlined } from '@ant-design/icons' -import styled from 'styled-components' +import React, { useEffect, useState } from 'react'; +import { NextPage } from 'next'; +import { useRouter } from 'next/router'; +import { Button, Col, Row } from 'antd'; +import { NotificationContainer, NotificationManager } from 'react-notifications'; -import ApiClient from '../../services/ApiClient' -import Loader from '../../components/Loader' -import Paragraph from '../../components/Paragraph' +import ApiClient from '../../services/ApiClient'; +import Loader from '../../components/Loader'; +import Paragraph from '../../components/Paragraph'; import { InversePrimaryButton, PrimaryButton -} from '../../components/PrimaryButton' -import { NotificationContainer, NotificationManager } from 'react-notifications' -import 'react-notifications/lib/notifications.css' +} from '../../components/PrimaryButton'; +import 'react-notifications/lib/notifications.css'; import { IndexContainer, IndexTitle, IndexParagraph, IndexSendContainer -} from './style' +} from './style'; const ValidateQR: NextPage<{}> = () => { - const [uploadedFile, setUploadedFile] = useState() - const [isProcessingRequest, setIsProcessingRequest] = useState(false) - const router = useRouter() - const uuid = router.query.id as string + const [uploadedFile, setUploadedFile] = useState(); + const [isProcessingRequest, setIsProcessingRequest] = useState(false); + const router = useRouter(); + const uuid = router.query.id as string; + useEffect(() => { try { - getFileFromUuid(uuid) + getFileFromUuid(uuid); } catch (error) { // console.log('error', error) } - }, [uuid]) + }, [uuid]); const getFileFromUuid = async (uuid: string, isDownload?: boolean) => { try { - let ipfsURL + let ipfsURL; + if (uploadedFile) { if (isDownload) { - const fileName = `${uuid || 'file'}.pdf` - const link = document.createElement('a') - link.href = window.URL.createObjectURL(uploadedFile) - link.download = fileName - link.click() + const fileName = `${uuid || 'file'}.pdf`; + const link = document.createElement('a'); + link.href = window.URL.createObjectURL(uploadedFile); + link.download = fileName; + link.click(); } - return { file: uploadedFile } + return { file: uploadedFile }; } else if (uuid) { - const response: any = await ApiClient.getIPSFFromUuid(uuid) - const ipfsStatus = response?.status - const ipfsError = response?.error - const ipfsMessage = response?.message - ipfsURL = response?.ipfsURL - if (ipfsStatus != 404 && ipfsMessage === 'OK') { - const file: any = await ApiClient.generateFile( - ipfsURL, - uuid, - isDownload - ) - setUploadedFile(file) - return { file } - } else return { file: null, ipfsError } + const response: any = await ApiClient.getIPSFFromUuid(uuid); + const ipfsStatus = response?.status; + const ipfsError = response?.error; + const ipfsMessage = response?.message; + ipfsURL = response?.ipfsURL; + + if (ipfsStatus !== 404 && ipfsMessage === 'OK') { + const file: any = await ApiClient.generateFile(ipfsURL, uuid, isDownload); + setUploadedFile(file); + return { file }; + } else return { file: null, ipfsError }; } } catch (error) { if (isDownload) { @@ -70,46 +67,49 @@ const ValidateQR: NextPage<{}> = () => { '', 5000, () => { - alert('callback') + alert('callback'); } - ) + ); } else { - throw error + throw error; } } - } + }; const sendIdentifier = async (uuid) => { try { if (uuid) { - setIsProcessingRequest(true) - const { file, ipfsError } = await getFileFromUuid(uuid) + setIsProcessingRequest(true); + const { file, ipfsError } = await getFileFromUuid(uuid); + if (ipfsError) { - const errorCode = ApiClient.getErrorCode(ipfsError) - router.push(`/error?error=${errorCode}`) - return + const errorCode = ApiClient.getErrorCode(ipfsError); + router.push(`/error?error=${errorCode}`); + return; } - const responseVerifyFile: any = await ApiClient.verifyFile(file) - const { error, message, hash, url, timestamp }: any = responseVerifyFile - if (message == 'OK') { + + const responseVerifyFile: any = await ApiClient.verifyFile(file); + const { error, message, hash, url, timestamp }: any = responseVerifyFile; + + if (message === 'OK') { router.push( `/success?timestamp=${timestamp}&url=${url}&hash=${hash}`, '/success' - ) + ); } else { - const errorCode = ApiClient.getErrorCode(error) - router.push(`/error?error=${errorCode}`) + const errorCode = ApiClient.getErrorCode(error); + router.push(`/error?error=${errorCode}`); } } } catch (error) { - const errorCode = ApiClient.getErrorCode(error) - router.push(`/error?error=${errorCode}`) + const errorCode = ApiClient.getErrorCode(error); + router.push(`/error?error=${errorCode}`); } - } + }; const renderLoadingView = () => { - return - } + return ; + }; const renderUploadFileView = () => { return ( @@ -121,8 +121,7 @@ const ValidateQR: NextPage<{}> = () => { xl={{ span: 14, push: 3 }} > - Te damos la bienvenida al Servicio de Verificación de documentos - en blockchain + Te damos la bienvenida al Servicio de Verificación de documentos en blockchain @@ -134,12 +133,9 @@ const ValidateQR: NextPage<{}> = () => { > - Izertis te permite contrastar cualquier documento notarizado en - blockchain en la Red T de Alastria. + Izertis te permite contrastar cualquier documento notarizado en blockchain en la Red T de Alastria.
- Para verificar el documento del que has escaneado el QR, debes - pulsar el botón VERIFICAR. Si lo deseas, puedes descargarte una - copia del mismo en el botón DESCARGAR. + Para verificar el documento del que has escaneado el QR, debes pulsar el botón VERIFICAR. Si lo deseas, puedes descargarte una copia del mismo en el botón DESCARGAR.
@@ -191,10 +187,10 @@ const ValidateQR: NextPage<{}> = () => { - ) - } + ); + }; - return isProcessingRequest ? renderLoadingView() : renderUploadFileView() -} + return isProcessingRequest ? renderLoadingView() : renderUploadFileView(); +}; -export default ValidateQR +export default ValidateQR; diff --git a/src/pages/validateQR/style.tsx b/src/pages/validateQR/style.tsx index 3d33ab7..485d919 100644 --- a/src/pages/validateQR/style.tsx +++ b/src/pages/validateQR/style.tsx @@ -1,5 +1,6 @@ import { Layout, Upload } from "antd" import styled from "styled-components" + import { DescriptionText, PageTitle } from "../../components/atomic_components/Text/variants" import { backgroundGray, black } from "../../theme/color" import media from '../../theme/media' diff --git a/src/services/ApiClient.ts b/src/services/ApiClient.ts index 59a6e2a..ac58bc2 100644 --- a/src/services/ApiClient.ts +++ b/src/services/ApiClient.ts @@ -1,97 +1,105 @@ -import axios from 'axios' +import axios from 'axios'; + export default class ApiClient { - private static API_NODE = process.env.CERTIFICATION_URL + private static API_NODE = process.env.CERTIFICATION_URL; + static API_NAMES = { UUID: `/uuid`, VERIFY: `/certifications/verify`, VERIFY_V2: `/v2/certifications/verify` - } + }; + static API_ERRORS = { ERR_BAD_REQUEST: 'ERR_BAD_REQUEST', ERR_NETWORK: 'ERR_NETWORK', NOT_FOUND_UUID: 'uuid.NOT_FOUND_UUID' - } - static async verifyFile(file: File) { - const formData = new FormData() - formData.append('file', file, file.name) - - let response + }; + static async verifyFile(file: File) { + const formData = new FormData(); + formData.append('file', file, file.name); + + let response; + let responseData; + try { response = await axios.put( `${ApiClient.API_NODE}${ApiClient.API_NAMES.VERIFY}`, formData - ) - if (!response.ok) throw '' + ); + if (!response.ok) throw new Error(''); } catch (error) { response = await axios.put( `${ApiClient.API_NODE}${ApiClient.API_NAMES.VERIFY_V2}`, formData - ) + ); } finally { - const responseData = await response.data - return responseData + responseData = await response.data; } + + return responseData; + } + static async getIPSFFromUuid(uuid) { - const url = `${ApiClient.API_NODE}${ApiClient.API_NAMES.UUID}/${uuid}` + const url = `${ApiClient.API_NODE}${ApiClient.API_NAMES.UUID}/${uuid}`; return axios.get(url).then(function (response) { - return response.data - }) + return response.data; + }); } static async generateFile(ipfsURL, uuid, isDownload?: boolean) { - const fileName = `${uuid}.pdf` + const fileName = `${uuid}.pdf`; const responseBlobIpfsFile = await axios({ url: ipfsURL, method: 'GET', responseType: 'blob' // important - }) - const file = new File([responseBlobIpfsFile.data], fileName) + }); + const file = new File([responseBlobIpfsFile.data], fileName); if (isDownload) { - const link = document.createElement('a') - link.href = window.URL.createObjectURL(responseBlobIpfsFile.data) - link.download = fileName - link.click() + const link = document.createElement('a'); + link.href = window.URL.createObjectURL(responseBlobIpfsFile.data); + link.download = fileName; + link.click(); } - return file + return file; } static getErrorCode(error: any) { - let errorCode = '' + let errorCode = ''; if (typeof error === 'object' && error?.code) { - const code = error?.code - const url = error?.config?.url + const code = error?.code; + const url = error?.config?.url; if (error.code === ApiClient.API_ERRORS.ERR_BAD_REQUEST) { if (url?.includes(ApiClient.API_NAMES.UUID)) { - errorCode = `${code}_UUID` + errorCode = `${code}_UUID`; } } else if (code === ApiClient.API_ERRORS.ERR_NETWORK) { - errorCode = `${code}_DOWNLOAD_IPFS` + errorCode = `${code}_DOWNLOAD_IPFS`; } } else if (typeof error === 'string') { if (error === ApiClient.API_ERRORS.NOT_FOUND_UUID) { - errorCode = error + errorCode = error; } else { - errorCode = error + errorCode = error; } } else { - errorCode = error.toString() + errorCode = error.toString(); } - return errorCode + return errorCode; } static getErrorDescription = ( error, formatFunction?: (errorMessage: string, errorCode?: string) => any ) => { - let errorMessage = '' + let errorMessage = ''; if (!error) { errorMessage = ` No encontramos este documento en la RedT de Alastria. Por favor, confirma tu fichero y vuelve a intentarlo. - ` - return + `; + return; } if (error.includes(ApiClient.API_ERRORS.ERR_NETWORK)) { if (error.includes('DOWNLOAD_IPFS')) { @@ -99,29 +107,29 @@ export default class ApiClient { Estamos teniendo problemas para obtener el documento para verificar en la RedT de Alastria. Por favor, vuelve a intentarlo más tarde. - ` + `; } else { errorMessage = ` Estamos teniendo problemas para verificar en la RedT de Alastria. Por favor, vuelve a intentarlo más tarde. - ` + `; } } else if (error.includes(ApiClient.API_ERRORS.ERR_BAD_REQUEST)) { errorMessage = ` El identificador o documento introducido no se encuentra en la RedT de Alastria. Por favor, confirma tu identificador y vuelve a intentarlo. - ` + `; } else if (error.includes(ApiClient.API_ERRORS.NOT_FOUND_UUID)) { errorMessage = ` El identificador introducido no se encuentra en la RedT de Alastria. Por favor, confirma tu identificador y vuelve a intentarlo. - ` + `; } else { errorMessage = ` No encontramos este documento en la RedT de Alastria. Por favor, confirma tu fichero y vuelve a intentarlo. - ` + `; } - return formatFunction ? formatFunction(errorMessage, error) : errorMessage - } + return formatFunction ? formatFunction(errorMessage, error) : errorMessage; + }; }