Created
April 10, 2024 08:09
-
-
Save singhAmandeep007/202dec009c78be83d87cd847379ed530 to your computer and use it in GitHub Desktop.
MSW request middleware error helper
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 { HttpResponse, JsonBodyType } from "msw"; | |
| export const errors = { | |
| resourceNotFound: ( | |
| body: JsonBodyType = { error: { message: "Resource not found" } } | |
| ) => HttpResponse.json(body, { status: 404 }), | |
| unauthorized: ( | |
| body: JsonBodyType = { | |
| error: { | |
| message: "Not authorized to access resource" | |
| } | |
| } | |
| ) => | |
| HttpResponse.json(body, { | |
| status: 403 | |
| }), | |
| internalServerError: ( | |
| body: JsonBodyType = { | |
| error: { | |
| message: "Internal server error" | |
| } | |
| } | |
| ) => | |
| HttpResponse.json(body, { | |
| status: 500 | |
| }), | |
| badRequest: ( | |
| body: JsonBodyType = { | |
| error: { | |
| message: "Bad request" | |
| } | |
| } | |
| ) => | |
| HttpResponse.json(body, { | |
| status: 400 | |
| }) | |
| }; | |
| export async function middleware(request: Request) { | |
| if (!request.headers.has("cookie") || !sessionStorage.getItem("isAuthenticated")) { | |
| throw errors.unauthorized(); | |
| } | |
| if (request.method === "GET") { | |
| // check if resource available | |
| // throw errors.resourceNotFound(); | |
| } | |
| if (request.method === "POST") { | |
| // check if request body is valid | |
| // throw errors.badRequest(); | |
| } | |
| if (request.method === "PUT") { | |
| // check if resource exists | |
| // throw errors.resourceNotFound(); | |
| // check if request body is valid | |
| // throw errors.badRequest(); | |
| } | |
| if (request.method === "DELETE") { | |
| // check if resource exists | |
| // throw errors.resourceNotFound(); | |
| } | |
| return request; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment