@opra/common
Version:
Opra common package
70 lines (69 loc) • 2.59 kB
JavaScript
import { omitUndefined } from '@jsopen/objects';
import { asMutable } from 'ts-gems';
import { OpraSchema } from '../../schema/index.js';
import { DataTypeMap } from '../common/data-type-map.js';
import { DocumentElement } from '../common/document-element.js';
import { CLASS_NAME_PATTERN, DECORATOR, kDataTypeMap } from '../constants.js';
import { DataType } from '../data-type/data-type.js';
import { WSOperationDecoratorFactory, } from '../decorators/ws-operation.decorator.js';
import { parseRegExp } from '../utils/parse-regexp.util.js';
/**
* WSOperation
*/
export const WSOperation = function (...args) {
// Decorator
if (!this) {
const [type, options] = args;
const decoratorChain = [];
return WSOperation[DECORATOR].call(undefined, decoratorChain, type, options);
}
// Constructor
const [resource, initArgs] = args;
DocumentElement.call(this, resource);
if (!CLASS_NAME_PATTERN.test(initArgs.name))
throw new TypeError(`Invalid operation name (${initArgs.name})`);
const _this = asMutable(this);
_this.types = _this.node[kDataTypeMap] = new DataTypeMap();
// noinspection JSConstantReassignment
_this.name = initArgs.name;
_this.description = initArgs.description;
if (initArgs.event)
this.event =
initArgs.event instanceof RegExp
? initArgs.event
: initArgs.event.startsWith('/')
? parseRegExp(initArgs.event)
: initArgs.event;
else
_this.event = this.name;
if (initArgs?.arguments) {
_this.arguments = initArgs.arguments.map(arg => {
const type = arg.type instanceof DataType
? arg.type
: _this.owner.node.getDataType(arg.type);
return { type, parameterIndex: arg.parameterIndex };
});
}
else
_this.arguments = [];
if (initArgs?.response)
_this.response =
initArgs.response instanceof DataType
? initArgs.response
: _this.owner.node.getDataType(initArgs.response);
};
/**
* @class WSOperation
*/
class WSOperationClass extends DocumentElement {
toJSON() {
return omitUndefined({
kind: OpraSchema.WSOperation.Kind,
description: this.description,
event: this.event,
arguments: this.arguments?.map(arg => arg.type.name ? arg.type.name : arg.type.toJSON()),
});
}
}
WSOperation.prototype = WSOperationClass.prototype;
WSOperation[DECORATOR] = WSOperationDecoratorFactory;