Created
February 27, 2024 18:12
-
-
Save JohnathanWeisner/4131b0f2104b13d5b0ceaeaafe7f9d48 to your computer and use it in GitHub Desktop.
mockfetch.js
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
import { comments } from "./mock-response.json"; | |
const mockResponse = (response) => { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve({ | |
success: 200, | |
json: () => | |
new Promise((resolve) => { | |
return resolve(response); | |
}), | |
}); | |
}, 2000); | |
}); | |
}; | |
export const fetch = (url, { body } = {}) => { | |
if (url === "/comments/verify") { | |
// Simulate a failing fetch | |
if (Math.random() > 0.5) { | |
return Promise.reject("No connection."); | |
} | |
if (!body?.postId) { | |
return Promise.reject("Missing postId"); | |
} | |
if (typeof body?.isVerified === "undefined") { | |
return Promise.reject("Missing isVerified"); | |
} | |
const { postId, isVerified } = body; | |
const comment = comments.find((comment) => comment.postId === postId); | |
if (!comment) { | |
return Promise.reject("No comment found with that postId."); | |
} | |
comment.isVerified = isVerified; | |
return mockResponse({ comment }); | |
} else if (url === "/comments") { | |
return mockResponse({ comments }); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment