Aller au contenu principal
Version : 9.x

Métadonnées de route

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

Les métadonnées de route vous permettent d'ajouter une propriété meta optionnelle spécifique à une route, qui sera disponible dans tous les paramètres des fonctions middleware.

Créer un routeur avec métadonnées typées

jsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean
}
export const appRouter = trpc.router<Context, Meta>();
jsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean
}
export const appRouter = trpc.router<Context, Meta>();

Exemple avec paramètres d'authentification par route

server.ts
tsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean;
}
export const appRouter = trpc
.router<Context, Meta>()
.middleware(async ({ meta, next, ctx }) => {
// only check authorization if enabled
if (meta?.hasAuth && !ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next();
})
.query('hello', {
meta: {
hasAuth: false,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
})
.query('protected-hello', {
meta: {
hasAuth: true,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
});
server.ts
tsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean;
}
export const appRouter = trpc
.router<Context, Meta>()
.middleware(async ({ meta, next, ctx }) => {
// only check authorization if enabled
if (meta?.hasAuth && !ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next();
})
.query('hello', {
meta: {
hasAuth: false,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
})
.query('protected-hello', {
meta: {
hasAuth: true,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
});