How to type async higher-order resolver in Typescript? #1802
Unanswered
nik-webdevelop
asked this question in
Q&A
Replies: 2 comments 2 replies
-
Hi, @nik-webdevelop. I gave it a try here but soon learned we need to ship better public-facing types to make higher-order resolvers a more pleasant experience. Thanks for making this surface. |
Beta Was this translation helpful? Give feedback.
2 replies
-
Here is my approach with authorization validation. // middleware.ts
import { DefaultBodyType, HttpResponse, HttpResponseResolver, PathParams } from "msw";
export function withAuth<RequestBodyType extends DefaultBodyType, ResponseBodyType extends DefaultBodyType>(
resolver: HttpResponseResolver
): HttpResponseResolver<PathParams, RequestBodyType, ResponseBodyType> {
// @ts-expect-error - ignore type checking for now
return async (args) => {
const { request } = args;
// get Authorization header
const authHeader = request.headers.get("Authorization");
// check if Authorization header exists
if (!authHeader) {
return new HttpResponse(null, { status: 401 });
}
// validate Bearer token format
const [scheme, token] = authHeader.split(" ");
if (scheme !== "Bearer" || !token) {
return new HttpResponse(
JSON.stringify({
error: "Invalid token format",
message: "Authorization header must be in the format: Bearer <token>",
}),
{
status: 401,
headers: {
"Content-Type": "application/json",
},
}
);
}
return resolver(args);
};
}
// posts.ts
import { http, HttpResponse } from "msw";
import { faker } from "@faker-js/faker/locale/en";
export const getPosts = http.get(
"/posts",
withAuth(({ request, cookies }) => {
const generatePosts = () => {
const posts = [];
for (let i = 0; i < 10; i++) {
posts.push({
id: faker.string.uuid(),
title: faker.lorem.sentence(),
userId: faker.string.uuid(),
});
}
return posts;
};
return HttpResponse.json(generatePosts());
})
); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
How can I type this higher-order resolver? I keep getting different errors no matter what approach I use
msw 2.0.0
ts 4.9.3
Beta Was this translation helpful? Give feedback.
All reactions