UNPKG

zod-to-x

Version:

Multi language types generation from Zod schemas.

61 lines (60 loc) 2.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Zod2XMixin = Zod2XMixin; /** * Extends a base class with additional functionality from a model class. * * @template T - The model class to extend from. * @template K - The base class to be extended. * @param Model - The model class providing additional properties or methods. * @param BaseClass - The base class to be extended. * @returns A new class that combines the functionality of the model and base classes. */ function extendBase(Model, BaseClass) { return class extends BaseClass { constructor(...args) { super(...args); Object.assign(this, new Model()); } }; } /** * Combines two class constructors into a single unified class. * The resulting class merges the properties and methods of both input classes. * * @template T - The first class type to unify. * @template K - The second class type to unify. * @param ModelA - The constructor of the first class. * @param ModelB - The constructor of the second class. * @returns A new class that combines the properties and methods of both input classes. */ function unifyModels(ModelA, ModelB) { return class { constructor() { Object.assign(this, new ModelA()); Object.assign(this, new ModelB()); } }; } /** * Combines multiple derived classes with a base class into a single class. * * @template T - A type extending `TClass`, representing the derived classes. * @template K - A type extending `TClass`, representing the base class. * @param DerivedClasses - An array of derived classes to be combined. * @param BaseClass - The base class to be extended. * @returns A new class that combines the functionality of the derived classes * and the base class. The resulting class has the constructor of the * base class and the combined instance types of all derived classes. * @throws {Error} If no derived classes are provided. */ function Zod2XMixin(DerivedClasses, BaseClass) { if (DerivedClasses.length === 0) { throw new Error("No derived classes provided"); } else { const CombinedDerivedClass = DerivedClasses.reduce((acc, curr) => unifyModels(acc, curr), class { }); return extendBase(CombinedDerivedClass, BaseClass); } }