|
| 1 | +import type { AnyContractProcedure } from '@orpc/contract' |
| 2 | +import type { OpenAPI } from './openapi' |
| 3 | +import { isProcedure } from '@orpc/server' |
| 4 | + |
| 5 | +const OPERATION_EXTENDER_SYMBOL = Symbol('ORPC_OPERATION_EXTENDER') |
| 6 | + |
| 7 | +export type OverrideOperationValue = OpenAPI.OperationObject |
| 8 | + | ((current: OpenAPI.OperationObject, procedure: AnyContractProcedure) => OpenAPI.OperationObject) |
| 9 | + |
| 10 | +export function setOperationExtender<T extends object>(o: T, extend: OverrideOperationValue): T { |
| 11 | + return new Proxy(o, { |
| 12 | + get(target, prop, receiver) { |
| 13 | + if (prop === OPERATION_EXTENDER_SYMBOL) { |
| 14 | + return extend |
| 15 | + } |
| 16 | + |
| 17 | + return Reflect.get(target, prop, receiver) |
| 18 | + }, |
| 19 | + }) |
| 20 | +} |
| 21 | + |
| 22 | +export function getOperationExtender(o: object): OverrideOperationValue | undefined { |
| 23 | + return (o as any)[OPERATION_EXTENDER_SYMBOL] as OverrideOperationValue |
| 24 | +} |
| 25 | + |
| 26 | +export function extendOperation(operation: OpenAPI.OperationObject, procedure: AnyContractProcedure): OpenAPI.OperationObject { |
| 27 | + const operationExtenders: OverrideOperationValue[] = [] |
| 28 | + |
| 29 | + for (const errorItem of Object.values(procedure['~orpc'].errorMap)) { |
| 30 | + const maybeExtender = getOperationExtender(errorItem as any) |
| 31 | + |
| 32 | + if (maybeExtender) { |
| 33 | + operationExtenders.push(maybeExtender) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if (isProcedure(procedure)) { |
| 38 | + for (const middleware of procedure['~orpc'].middlewares) { |
| 39 | + const maybeExtender = getOperationExtender(middleware) |
| 40 | + |
| 41 | + if (maybeExtender) { |
| 42 | + operationExtenders.push(maybeExtender) |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + let currentOperation = operation |
| 48 | + |
| 49 | + for (const extender of operationExtenders) { |
| 50 | + if (typeof extender === 'function') { |
| 51 | + currentOperation = extender(currentOperation, procedure) |
| 52 | + } |
| 53 | + else { |
| 54 | + currentOperation = { |
| 55 | + ...currentOperation, |
| 56 | + ...extender, |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return currentOperation |
| 62 | +} |
0 commit comments