Skip to content

Commit

Permalink
Reduce duplication in documents.text()
Browse files Browse the repository at this point in the history
Co-authored-by: Allan Lasser <[email protected]>
  • Loading branch information
eyeseast and allanlasser authored Apr 30, 2024
1 parent 29faa41 commit 63e3705
Showing 1 changed file with 20 additions and 32 deletions.
52 changes: 20 additions & 32 deletions src/lib/api/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,45 +102,33 @@ export async function text(
): Promise<DocumentText> {
// for errors
const empty = { updated: 0, pages: [] };

// for public documents, we can just fetch the asset
if (document.access === "public") {
const url = jsonUrl(document);
const resp = await fetch(url).catch(console.error);

if (!resp || isErrorCode(resp.status)) {
return empty;
}

return resp.json();
}

let url = jsonUrl(document);

// for public documents, we can just fetch the asset
// for private and organization docs, we need to hit the API first
// with credentials, and then fetch the returned location
let resp: Response | void = await fetch(jsonUrl(document), {
credentials: "include",
redirect: "error",
headers: {
Accept: "application/json",
},
}).catch(console.error);

if (!resp) {
return empty;
}

const { location } = await resp.json();

if (!location) {
return empty;
if (document.access !== "public") {
const resp: Response | void = await fetch(url, {
credentials: "include",
redirect: "error",
headers: {
Accept: "application/json",
},
}).catch(console.error);
if (!resp || isErrorCode(resp.status) {
return empty;
}
const { location } = await resp.json();
if (!location) {
return empty;
}
url = location;
}

resp = await fetch(location).catch(console.error);

const resp = await fetch(location).catch(console.error);
if (!resp || isErrorCode(resp.status)) {
return empty;
}

return resp.json();
}

Expand Down

0 comments on commit 63e3705

Please sign in to comment.