UNPKG

permix

Version:

Permix is a lightweight, framework-agnostic, type-safe permissions management library for JavaScript applications on the client and server sides.

60 lines (57 loc) 1.74 kB
import { initTRPC, TRPCError } from '@trpc/server'; import { c as createTemplate, a as createPermix$1 } from '../shared/permix.Q-O041RP.mjs'; import { c as createCheckContext, p as pick } from '../shared/permix.q13nxITM.mjs'; /** * Create a middleware function that checks permissions for TRPC routes. * * @link https://permix.letstri.dev/docs/integrations/trpc */ function createPermix({ forbiddenError = () => new TRPCError({ code: 'FORBIDDEN', message: 'You do not have permission to perform this action' }) } = {}) { const plugin = initTRPC.context().create(); function setup(rules) { return pick(createPermix$1(rules), ['check', 'dehydrate']); } function checkMiddleware(...params) { return plugin.middleware(async ({ ctx, next }) => { if (!ctx.permix) { throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: '[Permix] Instance not found. Please use the `setup` function.' }); } const hasPermission = ctx.permix.check(...params); if (!hasPermission) { const error = typeof forbiddenError === 'function' ? forbiddenError({ ...createCheckContext(...params), ctx }) : forbiddenError; if (!(error instanceof TRPCError)) { console.error('[Permix]: forbiddenError is not TRPCError'); throw new TRPCError({ code: 'FORBIDDEN', message: 'You do not have permission to perform this action' }); } throw error; } return next(); }); } function template(...params) { return createTemplate(...params); } return { setup, checkMiddleware, template }; } export { createPermix };