From 77c061bc0b8aecce7311ce820b3401c95797a589 Mon Sep 17 00:00:00 2001 From: jackyzha0 Date: Sun, 11 Apr 2021 11:40:44 -0700 Subject: working raw paste fetch --- frontend/src/http/useFetchPaste.js | 96 ++++++++++++++------------------------ 1 file changed, 35 insertions(+), 61 deletions(-) (limited to 'frontend/src/http/useFetchPaste.js') diff --git a/frontend/src/http/useFetchPaste.js b/frontend/src/http/useFetchPaste.js index ba482f9..8d40cbe 100644 --- a/frontend/src/http/useFetchPaste.js +++ b/frontend/src/http/useFetchPaste.js @@ -2,68 +2,42 @@ import {useEffect, useState} from 'react' import {fetchPaste, fmtDateStr} from './shared' import {LANGS} from "../components/renderers/Code"; -const useFetchPaste = (id) => { - const [loading, setLoading] = useState(true) - const [err, setErr] = useState() - const [requiresAuth, setRequiresAuth] = useState(false) - const [validPass, setValidPass] = useState(false) - const [result, setResult] = useState({ - title: 'fetching paste...', - content: '', - language: LANGS.detect, - expiry: '', - }) - - const handleErr = error => { - const resp = error.response - - // network err - if (!resp) { - setErr(error.toString()) - return - } - - // password protected - if (resp.status === 401) { - setRequiresAuth(true) - return - } - - // catch all - const errTxt = `${resp.status}: ${resp.data}` - setErr(errTxt) - } - - // callback to try verifying with password - const getWithPassword = (password, errorCallback) => { - fetchPaste(id, password) - .then(resp => { - setValidPass(true) - setStateFromData(resp.data) - }) - .catch(e => errorCallback(e.response.data)) +const resolvePaste = (id, password = "") => { + const response = { + data: { + title: '', + content: '', + language: LANGS.detect, + expiry: '', + }, + unauthorized: false, + error: '', } - - - const setStateFromData = (data) => { - document.title = data.title - setResult({ - title: data.title, - content: data.content, - language: data.language, - expiry: fmtDateStr(data.expiry) + return fetchPaste(id, password) + .then(resp => { + const data = resp.data + response.data = { + ...data, + expiry: fmtDateStr(data.expiry) + } + return response + }) + .catch(error => { + const resp = error.response + if (!resp) { + response.error = 'network error' + return + } + + if (resp.status === 401) { + response.error = 'unauthorized' + response.unauthorized = true + return + } + + response.error = `${resp.status}: ${resp.data}` + return response }) - } - - // initial fetch - useEffect(() => { - fetchPaste(id) - .then(resp => setStateFromData(resp.data)) - .catch(handleErr) - .finally(() => setLoading(false)) - }, [id]) - - return { loading, err, requiresAuth, validPass, getWithPassword, result } } -export default useFetchPaste \ No newline at end of file +export default resolvePaste \ No newline at end of file -- cgit v1.2.3