@opra/common
Version:
Opra common package
76 lines (75 loc) • 2.6 kB
JavaScript
import { omit } from '@jsopen/objects';
import { OpraSchema } from '../../schema/index.js';
import { RPC_CONTROLLER_METADATA } from '../constants.js';
const augmentationRegistry = [];
export function RpcOperationDecoratorFactory(decoratorChain, payloadType, options) {
let inResponse = false;
/**
*
*/
const decorator = ((target, propertyKey) => {
if (typeof propertyKey !== 'string')
throw new TypeError(`Symbol properties can not be decorated`);
const operationMetadata = {
kind: OpraSchema.RpcOperation.Kind,
channel: propertyKey,
payloadType,
...omit(options, ['kind', 'payloadType']),
};
const controllerMetadata = (Reflect.getOwnMetadata(RPC_CONTROLLER_METADATA, target.constructor) || {});
controllerMetadata.operations = controllerMetadata.operations || {};
controllerMetadata.operations[propertyKey] = operationMetadata;
for (const fn of decoratorChain)
fn(operationMetadata, target, propertyKey);
Reflect.defineMetadata(RPC_CONTROLLER_METADATA, controllerMetadata, target.constructor);
});
/**
*
*/
decorator.UseType = (...type) => {
decoratorChain.push((meta) => {
meta.types = meta.types || [];
meta.types.push(...type);
});
return decorator;
};
/**
*
*/
decorator.Header = (name, arg1) => {
decoratorChain.push((meta) => {
const headerMetadata = typeof arg1 === 'string' || typeof arg1 === 'function'
? {
name,
type: arg1,
}
: { ...arg1, name };
const subMeta = inResponse ? meta.response : meta;
if (subMeta.headers) {
subMeta.headers = subMeta.headers.filter(p => String(p.name) !== String(name));
}
else
subMeta.headers = [];
subMeta.headers.push(headerMetadata);
});
return decorator;
};
/**
*
*/
decorator.Response = (_payloadType, _options) => {
decoratorChain.push((meta) => {
inResponse = true;
meta.response = {
..._options,
payloadType: _payloadType,
};
});
return decorator;
};
augmentationRegistry.forEach(fn => fn(decorator, decoratorChain, payloadType, options));
return decorator;
}
RpcOperationDecoratorFactory.augment = function (fn) {
augmentationRegistry.push(fn);
};