// --- CLIENT -----
// My tanstack queryOptions
export const profileOptions = (username: string) => queryOptions({
queryKey: queryKeys.profileKey(username),
queryFn: () => getUserProfile({ data: { username } }),
});
// --- SERVER -----
interface BaseDataWithUsername {
username: string;
[key: string]: any;
}
export const authorizationMiddleware = createMiddleware()
.validator((rawData: unknown): BaseDataWithUsername => {
if (typeof rawData !== "object" || rawData === null) throw new Error("Bad request");
const data = rawData as Record<string, any>;
if (!data.username) throw notFound();
return data as BaseDataWithUsername; // Here I type data
})
.server(async ({ next, data: { username } }) => {
// whatever but here username and data are nicely typed, yay :)
return next({ context: { user: user, currentUser: session?.user } });
});
export const getUserProfile = createServerFn({ method: "GET" })
.middleware([authorizationMiddleware])
.validator((data) => data) // data here is `any` why ?
// but if this validator is not present then the data in .handler will be inferred to have at least username: string, and [key: string]: any;
.handler(async ({ context: { currentUser, user }, data }) => {
// something something
});
// --- CLIENT -----
// My tanstack queryOptions
export const profileOptions = (username: string) => queryOptions({
queryKey: queryKeys.profileKey(username),
queryFn: () => getUserProfile({ data: { username } }),
});
// --- SERVER -----
interface BaseDataWithUsername {
username: string;
[key: string]: any;
}
export const authorizationMiddleware = createMiddleware()
.validator((rawData: unknown): BaseDataWithUsername => {
if (typeof rawData !== "object" || rawData === null) throw new Error("Bad request");
const data = rawData as Record<string, any>;
if (!data.username) throw notFound();
return data as BaseDataWithUsername; // Here I type data
})
.server(async ({ next, data: { username } }) => {
// whatever but here username and data are nicely typed, yay :)
return next({ context: { user: user, currentUser: session?.user } });
});
export const getUserProfile = createServerFn({ method: "GET" })
.middleware([authorizationMiddleware])
.validator((data) => data) // data here is `any` why ?
// but if this validator is not present then the data in .handler will be inferred to have at least username: string, and [key: string]: any;
.handler(async ({ context: { currentUser, user }, data }) => {
// something something
});