UNPKG

@opra/common

Version:
86 lines (85 loc) 3.11 kB
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 { RpcOperationDecoratorFactory, } from '../decorators/rpc-operation.decorator.js'; /** * RpcOperation */ export const RpcOperation = function (...args) { // Decorator if (!this) { const [payloadType, options] = args; const decoratorChain = []; return RpcOperation[DECORATOR].call(undefined, decoratorChain, payloadType, 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.headers = []; _this.types = _this.node[kDataTypeMap] = new DataTypeMap(); _this.name = initArgs.name; _this.description = initArgs.description; _this.channel = initArgs.channel; if (initArgs?.payloadType) { _this.payloadType = initArgs?.payloadType instanceof DataType ? initArgs.payloadType : _this.owner.node.getDataType(initArgs.payloadType); } if (initArgs?.keyType) { _this.keyType = initArgs?.keyType instanceof DataType ? initArgs.keyType : _this.owner.node.getDataType(initArgs.keyType); } }; /** * @class RpcOperation */ class RpcOperationClass extends DocumentElement { findHeader(paramName) { const paramNameLower = paramName.toLowerCase(); let prm; for (prm of this.headers) { if (typeof prm.name === 'string') { prm._nameLower = prm._nameLower || prm.name.toLowerCase(); if (prm._nameLower === paramNameLower) return prm; } if (prm.name instanceof RegExp && prm.name.test(paramName)) return prm; } } toJSON() { const out = omitUndefined({ kind: OpraSchema.RpcOperation.Kind, description: this.description, channel: this.channel, payloadType: this.payloadType.name ? this.payloadType.name : this.payloadType.toJSON(), keyType: this.keyType ? this.keyType.name ? this.keyType.name : this.keyType.toJSON() : undefined, response: this.response?.toJSON(), }); if (this.headers.length) { out.headers = []; for (const prm of this.headers) { out.headers.push(prm.toJSON()); } } return out; } } RpcOperation.prototype = RpcOperationClass.prototype; RpcOperation[DECORATOR] = RpcOperationDecoratorFactory;