add headers and middleware

This commit is contained in:
Ruidy 2024-12-12 23:49:52 +01:00
parent ae63d45fe6
commit 767471f2bb
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
6 changed files with 46 additions and 6 deletions

View file

@ -0,0 +1,4 @@
export default function useGreeting(text: string) {
const { $client } = useNuxtApp();
return $client.hello.useQuery({ text });
}

View file

@ -1,7 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const { $client } = useNuxtApp(); const { data } = useGreeting("chef");
const { data } = await $client.hello.useQuery({ text: "chef" });
</script> </script>
<template> <template>

View file

@ -2,6 +2,7 @@ import { createTRPCNuxtClient, httpBatchLink } from "trpc-nuxt/client";
import type { AppRouter } from "~/server/trpc/routers"; import type { AppRouter } from "~/server/trpc/routers";
export default defineNuxtPlugin(() => { export default defineNuxtPlugin(() => {
const headers = useRequestHeaders();
/** /**
* createTRPCNuxtClient adds a `useQuery` composable * createTRPCNuxtClient adds a `useQuery` composable
* built on top of `useAsyncData`. * built on top of `useAsyncData`.
@ -10,6 +11,13 @@ export default defineNuxtPlugin(() => {
links: [ links: [
httpBatchLink({ httpBatchLink({
url: "/api/trpc", url: "/api/trpc",
headers() {
// add custom headers here
return {
Authorization: "Bearer token",
...headers,
};
},
}), }),
], ],
}); });

View file

@ -4,6 +4,19 @@ import type { inferAsyncReturnType } from "@trpc/server";
* Creates context for an incoming request * Creates context for an incoming request
* @link https://trpc.io/docs/context * @link https://trpc.io/docs/context
*/ */
export const createContext = () => ({}); export async function createContext(event: H3Event) {
const authorization = getRequestHeader(event, "authorization");
async function getUserFromHeader() {
if (authorization) {
console.log("authorization:", authorization);
return { isAdmin: true };
}
return null;
}
const user = await getUserFromHeader();
return {
user,
};
}
export type Context = inferAsyncReturnType<typeof createContext>; export type Context = inferAsyncReturnType<typeof createContext>;

View file

@ -1,8 +1,10 @@
import type { inferRouterOutputs } from "@trpc/server";
import { z } from "zod"; import { z } from "zod";
import { publicProcedure, router } from "../trpc"; import { publicProcedure, privateProcedure, router } from "../trpc";
export const appRouter = router({ export const appRouter = router({
hello: publicProcedure // hello: publicProcedure
hello: privateProcedure
.input( .input(
z.object({ z.object({
text: z.string().nullish(), text: z.string().nullish(),
@ -17,3 +19,4 @@ export const appRouter = router({
// export type definition of API // export type definition of API
export type AppRouter = typeof appRouter; export type AppRouter = typeof appRouter;
export type RouterOutput = inferRouterOutputs<AppRouter>;

View file

@ -1,5 +1,7 @@
import { initTRPC } from "@trpc/server"; import { initTRPC } from "@trpc/server";
import type { Context } from "~/server/trpc/context"; import type { Context } from "~/server/trpc/context";
import { TRPCError } from "@trpc/server";
// import { authMiddleware } from "~/server/trpc/middleware";
const t = initTRPC.context<Context>().create(); const t = initTRPC.context<Context>().create();
@ -9,3 +11,15 @@ const t = initTRPC.context<Context>().create();
export const publicProcedure = t.procedure; export const publicProcedure = t.procedure;
export const router = t.router; export const router = t.router;
export const middleware = t.middleware; export const middleware = t.middleware;
export const authMiddleware = middleware(({ next, ctx }) => {
if (!ctx.user?.isAdmin) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
user: ctx.user,
},
});
});
export const privateProcedure = t.procedure.use(authMiddleware);