Skip to content

Instantly share code, notes, and snippets.

@singhAmandeep007
Created April 10, 2024 08:09
Show Gist options
  • Select an option

  • Save singhAmandeep007/202dec009c78be83d87cd847379ed530 to your computer and use it in GitHub Desktop.

Select an option

Save singhAmandeep007/202dec009c78be83d87cd847379ed530 to your computer and use it in GitHub Desktop.
MSW request middleware error helper
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