NuxtN
Nuxt11mo ago
4 replies
Untlsn

Forced typesafe body

Has anyone tried to make inferable typesafe body using nuxt $fetch?

Most of the methods I tried did not work. The only one that seems promising is a wrapper around defineEventHandler that pollutes response

There is a simple prototype:

export function definePostEventHandler<TInput, TOutput>(
  input: (rawBody: unknown) => TInput,
  handler: (body: TInput, event: H3Event<EventHandlerRequest>) => Promise<TOutput>,
): EventHandler<EventHandlerRequest, Promise<[TOutput, TInput]>> {
  return defineEventHandler(async (event) => {
    return [handler(input(readBody(event)), event)] as any;
  });
}

// If you don't want input validation
definePostEventHandler.any = <T>(rawBody: unknown) => rawBody as T;


Usage:

export default definePostEventHandler(definePostEventHandler.any<{ value: string }>, async (body) => {
  return {
    long: `Hello ${JSON.stringify(body)}`,
  };
});


Frontend access:

type InternalApiPostKey = keyof {
  [K in keyof InternalApi as InternalApi[K] extends { post: any } ? K : never]: unknown
};

export async function fetchPost<TKey extends InternalApiPostKey>(key: TKey, data: InternalApi[TKey]['post'][1]) {
  const [response] = await ($fetch as any)(key, {
    method: 'POST',
    data,
  });

  return response;
}
Was this page helpful?