Skip to content

Commit

Permalink
Fix for 2825
Browse files Browse the repository at this point in the history
New utility method for converting to atob with stringification checks
Updated Parser for Blobs
  • Loading branch information
bcameron1231 committed Nov 13, 2023
1 parent e29b6a9 commit 870e724
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
18 changes: 17 additions & 1 deletion packages/core/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,23 @@ export function hOP<T extends string>(o: any, p: T): boolean {
return Object.hasOwnProperty.call(o, p);
}


/**
* @returns validates and returns a valid atob conversion
*/
export function parseToAtob(str: string): string {
const base64Regex = /^[A-Za-z0-9+/]+={0,2}$/;
try {
// test if str has been JSON.stringified
const parsed = JSON.parse(str);
if(base64Regex.test(parsed)){
return atob(parsed);
}
return null;
} catch (err) {
// Not a valid JSON string, check if it's a standalone Base64 string
return base64Regex.test(str) ? atob(str) : null;
}
}

/**
* Generates a ~unique hash code
Expand Down
18 changes: 16 additions & 2 deletions packages/queryable/behaviors/parsers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Queryable } from "../queryable.js";
import { hOP, TimelinePipe } from "@pnp/core";
import { hOP, TimelinePipe, parseToAtob } from "@pnp/core";
import { isFunc } from "@pnp/core";

export function DefaultParse(): TimelinePipe {
Expand All @@ -25,7 +25,21 @@ export function TextParse(): TimelinePipe {

export function BlobParse(): TimelinePipe {

return parseBinderWithErrorCheck(r => r.blob());
return parseBinderWithErrorCheck( async (response) => {
const responseBody = parseToAtob(await response.clone().text());
// handle batch responses for things that are base64, like photos https://github.com/pnp/pnpjs/issues/2825
if(responseBody){
// Create an array buffer from the binary string
const arrayBuffer = new ArrayBuffer(responseBody.length);
const uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < responseBody.length; i++) {
uint8Array[i] = responseBody.charCodeAt(i);
}
// Create a Blob from the array buffer
return new Blob([arrayBuffer], {type:response.headers.get("Content-Type")});
}
return response.blob();
});
}

export function JSONParse(): TimelinePipe {
Expand Down

0 comments on commit 870e724

Please sign in to comment.