How to automatically generate a GitHub file's sha without using the GitHub API

22 views Asked by At

This topic has been talked about before, but none of the answers fit my needs. So I need new answers...

So, my project needs many, many, things to work (which makes it a bit slow), and one of them is the GitHub API, I need to fetch an image from the GitHub API but I do res.blob() after the request is finished, and I use the application/vnd.github.raw+json value with the Accept header, which makes the GitHub API not return the file's sha. Is there anything I can do to generate the sha myself, given the blob?

This is the code I currently have after the GET request:

.then(res => res.blob()).then(async dat => {
   console.log(dat)
   let base, customSha
   await read(dat).then(dat => { base = JSON.parse(dat).base; customSha = JSON.parse(dat).sha })
   source = `data:image/png;base64,${base}`;
   blobSha = customSha;
   console.log(base);
})

The read() function:

async function read(blob) {
    return new Promise(async (resolve, reject) => {
        let reader = new FileReader();
        let final = {}
        reader.onloadend = async () => {
            const base64String = reader.result.split(',')[1];
            final.base = base64String
            resolve(JSON.stringify(final))
        }
        reader.onerror = reject
        let content = await blob.text();
        let header = `blob ${content.bytesize}\u0000`;
        let combined = header + content;
        const encoded = new TextEncoder().encode(combined);
        let hashBuffer = await crypto.subtle.digest("SHA-1", encoded)

        const hashArray = Array.from(new Uint8Array(hashBuffer))
        const hash = hashArray
            .map((b) => b.toString(16).padStart(2, "0"))
            .join("")
        final.sha = hash
        reader.readAsDataURL(blob);
    })
}

Here I tried using the TextEncoder class to get a sha using a string composed of a combination of blob , the blob.text()'s bytesize (not sure if that returns something, that part was from an answer on another similar question), a \u0000 character, and finally the result of blob.text().

I expected the sha to be the same as the one on GitHub and that I'll automatically be able to edit the file using that sha later on.

Which, well, didn't work. So I need some help with that.

0

There are 0 answers