UNPKG

trpc-shield

Version:

tRPC permissions as another layer of abstraction!

51 lines 2.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateMiddlewareFromRuleTree = generateMiddlewareFromRuleTree; /** * * @param ruleTree * @param options * * Generates middleware from given rules. * */ function generateMiddlewareFromRuleTree(ruleTree, options) { return (opts) => { var _a, _b, _c; const { next, ctx, type, path, input, getRawInput } = opts; const rawInput = getRawInput(); const opWithPath = path.split('.'); const opName = opWithPath[opWithPath.length - 1]; const keys = Object.keys(ruleTree); let rule; if (keys.includes('query') || keys.includes('mutation')) { //@ts-ignore rule = (_a = ruleTree === null || ruleTree === void 0 ? void 0 : ruleTree[type]) === null || _a === void 0 ? void 0 : _a[opName]; } else { const namespace = opWithPath[0]; const tree = ruleTree[namespace]; if ((_b = tree === null || tree === void 0 ? void 0 : tree[type]) === null || _b === void 0 ? void 0 : _b[opName]) { rule = (_c = tree === null || tree === void 0 ? void 0 : tree[type]) === null || _c === void 0 ? void 0 : _c[opName]; } } rule = rule || options.fallbackRule; if (rule) { return rule === null || rule === void 0 ? void 0 : rule.resolve(ctx, type, path, input, rawInput, options).then((result) => { if (result instanceof Error) throw result; // Handle context extension if (typeof result === 'object' && result !== null && 'ctx' in result) { // Merge context extension and call next with updated context const extendedCtx = { ...ctx, ...result.ctx }; return next({ ctx: extendedCtx }); } if (!result) throw options.fallbackError; return next(); }); } return next(); }; } //# sourceMappingURL=generator.js.map