Created
August 11, 2020 09:35
-
-
Save kacpak/dbe95eb446376b8dc59905b290e6fe4c to your computer and use it in GitHub Desktop.
This file contains 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
// ==UserScript== | |
// @name Request Mocker | |
// @description Edit this script to mock requests on you site (also edit @match) | |
// @match *://*/* | |
// @grant none | |
// @version 1.0 | |
// @author Mateusz Kasprzak | |
// @require https://unpkg.com/msw@0.20.4/lib/umd/index.js | |
// ==/UserScript== | |
const {rest, setupWorker} = MockServiceWorker; | |
const handlers = [ | |
rest.post('/login', (req, res, ctx) => { | |
// Persist user's authentication in the session | |
sessionStorage.setItem('is-authenticated', true) | |
return res( | |
// Respond with a 200 status code | |
ctx.status(200), | |
) | |
}), | |
rest.get('/user', (req, res, ctx) => { | |
// Check if the user is authenticated in this session | |
const isAuthenticated = sessionStorage.getItem('is-authenticated') | |
if (!isAuthenticated) { | |
// If not authenticated, respond with a 403 error | |
return res( | |
ctx.status(403), | |
ctx.json({ | |
errorMessage: 'Not authorized', | |
}), | |
) | |
} | |
// If authenticated, return a mocked user details | |
return res( | |
ctx.status(200), | |
ctx.json({ | |
username: 'admin', | |
}), | |
) | |
}), | |
] | |
setupWorker(...handlers).start({ | |
serviceWorker: { | |
// Points to the custom location of the Service Worker file. | |
url: 'https://unpkg.com/msw@0.20.4/lib/umd/mockServiceWorker.js' | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment