Created
March 4, 2022 06:20
-
-
Save sunnymui/6144d879700fac39bd2a1dc5ef325902 to your computer and use it in GitHub Desktop.
Mock a File Upload Server Response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mockUpload = (files = []) => | |
// return a promise so we can use async features like then/async/await | |
new Promise((resolve, reject) => { | |
// throw error if no files | |
if (!files || !files.length) { | |
return setTimeout( | |
() => reject(new Error('Not found')), | |
1250 | |
); | |
} | |
// create a mock server response | |
const responseInit = { "status" : 200 , "statusText" : "OK" }; | |
const fakeBlob = [JSON.stringify({response:"Test"}, null, 2)]; | |
setTimeout(() => resolve( | |
new Response(new Blob(fakeBlob, {type : 'application/json'}), responseInit) | |
), 1250); | |
}); | |
// do a fake upload | |
const uploadedFiles = [{thing: ""}]; | |
mockUpload(uploadedFiles) | |
.then((res) => { | |
if (res.status !== 200) { | |
throw new Error('Service error!') | |
} | |
return res.blob(); | |
}) | |
.then((blob) => blob.text()) | |
.then((result) => { | |
// upload happened successfully! | |
console.log('success', result); | |
}).catch((error) => { | |
// something went wrong with the api! | |
console.log(error.toString()) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment