@opra/common
Version:
Opra common package
80 lines (79 loc) • 2.76 kB
JavaScript
import { isConstructor, omit } from '@jsopen/objects';
import { OpraSchema } from '../../schema/index.js';
import { MQ_CONTROLLER_METADATA } from '../constants.js';
const augmentationRegistry = [];
export function MQOperationDecoratorFactory(decoratorChain, type, 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.MQOperation.Kind,
channel: propertyKey,
type,
...omit(options, ['kind', 'type']),
};
const controllerMetadata = (Reflect.getOwnMetadata(MQ_CONTROLLER_METADATA, target.constructor) || {});
controllerMetadata.operations = controllerMetadata.operations || {};
controllerMetadata.operations[propertyKey] = operationMetadata;
for (const fn of decoratorChain)
fn(operationMetadata, target, propertyKey);
Reflect.defineMetadata(MQ_CONTROLLER_METADATA, controllerMetadata, target.constructor);
});
/**
*
*/
decorator.UseType = (...types) => {
decoratorChain.push((meta) => {
meta.types = meta.types || [];
meta.types.push(...types);
});
return decorator;
};
/**
*
*/
decorator.Header = (name, arg1) => {
decoratorChain.push((meta) => {
const headerMetadata = typeof arg1 === 'string' || typeof arg1 === 'function'
? {
name,
type: arg1,
}
: { ...arg1, name };
if (isConstructor(headerMetadata.type))
headerMetadata.designType = headerMetadata.type;
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 = (_type, _options) => {
decoratorChain.push((meta) => {
inResponse = true;
meta.response = {
..._options,
type: _type,
};
if (isConstructor(_type))
meta.response.designType = _type;
});
return decorator;
};
augmentationRegistry.forEach(fn => fn(decorator, decoratorChain, type, options));
return decorator;
}
MQOperationDecoratorFactory.augment = function (fn) {
augmentationRegistry.push(fn);
};