Options
All
  • Public
  • Public/Protected
  • All
Menu

Module @marcj/marshal

Core

npm version

This is the main module of marshal you can install in your frontend and/or backend project.

npm install @marcj/marshal

See the main documentation at marshal.marcj.dev for more information.

Index

References

Classes

Interfaces

Type aliases

Decorator Variables

Other Variables

Decorator Functions

Decorator Example one direction. ```typescript class JobConfig { @f.forward(() => Job) //forward necessary since circular dependency @ParentReference() job: Job; } class Job { @f config: JobConfig; } ``` Example circular parent-child setup. ```typescript export class PageClass { @f.uuid() id: string = uuid(); @f name: string; @f.forwardArray(() => PageClass) //forward necessary since circular dependency children: PageClass[] = []; @f.forward(() => PageClass).optional() //forward necessary since circular dependency @ParentReference() parent?: PageClass; constructor(name: string) { this.name = name; } ``` todo: Move this to @f api. Functions

Other Functions

Object literals

References

BackReferenceOptions

Re-exports BackReferenceOptions

CacheJitPropertyConverter

Re-exports CacheJitPropertyConverter

ClassSchema

Re-exports ClassSchema

DatabaseName

Re-exports DatabaseName

Entity

Re-exports Entity

EntityIndex

Re-exports EntityIndex

FieldDecoratorResult

Re-exports FieldDecoratorResult

FieldDecoratorWrapper

Re-exports FieldDecoratorWrapper

JitConverterOptions

Re-exports JitConverterOptions

JitPropertyConverter

Re-exports JitPropertyConverter

MainDecorator

Re-exports MainDecorator

MarshalGlobal

Re-exports MarshalGlobal

MultiIndex

Re-exports MultiIndex

OnLoad

Re-exports OnLoad

ParentReference

Re-exports ParentReference

PartialField

Re-exports PartialField

Patcher

Re-exports Patcher

PropertyCompilerSchema

Re-exports PropertyCompilerSchema

PropertySchema

Re-exports PropertySchema

PropertySchemaSerialized

Re-exports PropertySchemaSerialized

PropertyValidator

Re-exports PropertyValidator

PropertyValidatorError

Re-exports PropertyValidatorError

RegisteredEntities

Re-exports RegisteredEntities

ToClassState

Re-exports ToClassState

TypeCheckerCompiler

Re-exports TypeCheckerCompiler

TypeCheckerCompilerContext

Re-exports TypeCheckerCompilerContext

TypeConverterCompiler

Re-exports TypeConverterCompiler

TypeConverterCompilerContext

Re-exports TypeConverterCompilerContext

TypedArray

Re-exports TypedArray

TypedArrayClassType

Re-exports TypedArrayClassType

Types

Re-exports Types

ValidationError

Re-exports ValidationError

ValidationFailed

Re-exports ValidationFailed

applyAndReturnPatches

Re-exports applyAndReturnPatches

applyPatch

Re-exports applyPatch

argumentClassToPlain

Re-exports argumentClassToPlain

argumentPlainToClass

Re-exports argumentPlainToClass

arrayBufferFrom

Re-exports arrayBufferFrom

arrayBufferTo

Re-exports arrayBufferTo

arrayBufferToBase64

Re-exports arrayBufferToBase64

base64ToArrayBuffer

Re-exports base64ToArrayBuffer

base64ToTypedArray

Re-exports base64ToTypedArray

capitalizeFirstLetter

Re-exports capitalizeFirstLetter

classToPlain

Re-exports classToPlain

cloneClass

Re-exports cloneClass

compilerConvertClassToX

Re-exports compilerConvertClassToX

compilerRegistry

Re-exports compilerRegistry

compilerToNumber

Re-exports compilerToNumber

compilerToString

Re-exports compilerToString

compilerXToClass

Re-exports compilerXToClass

compilerXToUnionClass

Re-exports compilerXToUnionClass

createClassSchema

Re-exports createClassSchema

createClassToXFunction

Re-exports createClassToXFunction

createJITConverterFromPropertySchema

Re-exports createJITConverterFromPropertySchema

createXToClassFunction

Re-exports createXToClassFunction

executeCheckerCompiler

Re-exports executeCheckerCompiler

executeCompiler

Re-exports executeCompiler

f

Re-exports f

field

Re-exports field

forwardRef

Re-exports forwardRef

getClassSchema

Re-exports getClassSchema

getClassTypeFromInstance

Re-exports getClassTypeFromInstance

getDataCheckerJS

Re-exports getDataCheckerJS

getDataConverterJS

Re-exports getDataConverterJS

getEntityName

Re-exports getEntityName

handleCustomValidator

Re-exports handleCustomValidator

isArray

Re-exports isArray

isClassInstance

Re-exports isClassInstance

isPropertyValidator

Re-exports isPropertyValidator

isRegisteredEntity

Re-exports isRegisteredEntity

isTypedArray

Re-exports isTypedArray

jitClassToPlain

Re-exports jitClassToPlain

jitPartial

Re-exports jitPartial

jitPartialClassToPlain

Re-exports jitPartialClassToPlain

jitPartialPlainToClass

Re-exports jitPartialPlainToClass

jitPlainToClass

Re-exports jitPlainToClass

jitValidate

Re-exports jitValidate

jitValidatePartial

Re-exports jitValidatePartial

jitValidateProperty

Re-exports jitValidateProperty

methodResultClassToPlain

Re-exports methodResultClassToPlain

methodResultPlainToClass

Re-exports methodResultPlainToClass

moment

Re-exports moment

nodeBufferToArrayBuffer

Re-exports nodeBufferToArrayBuffer

nodeBufferToTypedArray

Re-exports nodeBufferToTypedArray

partialClassToPlain

Re-exports partialClassToPlain

partialPlainToClass

Re-exports partialPlainToClass

plainToClass

Re-exports plainToClass

propertyClassToPlain

Re-exports propertyClassToPlain

registerCheckerCompiler

Re-exports registerCheckerCompiler

registerConverterCompiler

Re-exports registerConverterCompiler

reserveVariable

Re-exports reserveVariable

resolveClassTypeOrForward

Re-exports resolveClassTypeOrForward

resolvePropertyCompilerSchema

Re-exports resolvePropertyCompilerSchema

shallowCloneObject

Re-exports shallowCloneObject

type

Re-exports type

typedArrayMap

Re-exports typedArrayMap

typedArrayNamesMap

Re-exports typedArrayNamesMap

typedArrayToBase64

Re-exports typedArrayToBase64

typedArrayToBuffer

Re-exports typedArrayToBuffer

uuid

Re-exports uuid

validate

Re-exports validate

validateMethodArgs

Re-exports validateMethodArgs

validatedPlainToClass

Re-exports validatedPlainToClass

validates

Re-exports validates

validatesFactory

Re-exports validatesFactory

validationRegistry

Re-exports validationRegistry

Type aliases

FieldTypes

FieldTypes: String | Number | Date | ClassType<any> | ForwardedRef<any>

ForwardRefFn

ForwardRefFn<T>: () => T

Type parameters

  • T

Type declaration

    • (): T
    • Returns T

IndexOptions

IndexOptions: Partial<{ fulltext: boolean; sparse: boolean; spatial: boolean; synchronize: boolean; unique: boolean; where: string }>

Mutable

Mutable<T>: {}

Type parameters

  • T

Type declaration

PartialField

PartialField<T>: {} & {}

Type for @f.partial().

Differs to standard Partial<> in a way that it supports sub class fields using dot based paths (like mongoDB)

Type parameters

  • T

TypeCheckerCompiler

TypeCheckerCompiler: (accessor: string, property: PropertyCompilerSchema, utils: { context: TypeCheckerCompilerContext; path: string; raise: (code: string, message: string) => string; reserveVariable: () => string }) => string | { context: {}; template: string }

Type declaration

    • (accessor: string, property: PropertyCompilerSchema, utils: { context: TypeCheckerCompilerContext; path: string; raise: (code: string, message: string) => string; reserveVariable: () => string }): string | { context: {}; template: string }
    • Parameters

      • accessor: string
      • property: PropertyCompilerSchema
      • utils: { context: TypeCheckerCompilerContext; path: string; raise: (code: string, message: string) => string; reserveVariable: () => string }
        • context: TypeCheckerCompilerContext
        • path: string
        • raise: (code: string, message: string) => string
            • (code: string, message: string): string
            • Parameters

              • code: string
              • message: string

              Returns string

        • reserveVariable: () => string
            • (): string
            • Returns string

      Returns string | { context: {}; template: string }

TypeCheckerCompilerContext

TypeCheckerCompilerContext: Map<string, any>

TypeConverterCompiler

TypeConverterCompiler: (setter: string, accessor: string, property: PropertyCompilerSchema, reserveVariable: () => string, context: TypeConverterCompilerContext) => string | { context: {}; template: string }

Type declaration

TypeConverterCompilerContext

TypeConverterCompilerContext: Map<string, any>

Types

Types: "objectId" | "uuid" | "class" | "union" | "moment" | "date" | "string" | "boolean" | "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "arrayBuffer" | "number" | "enum" | "any"

Decorator Variables

Const f

f: MainDecorator & FieldDecoratorResult<any> = fRaw as any

This is the main decorator to define a properties on class or arguments on methods.

class SubModel {
   @f label: string;
}

export enum Plan {
  DEFAULT,
  PRO,
  ENTERPRISE,
}

class SimpleModel {
  @f.primary().uuid()
  id: string = uuid();

  @f.array(String)
  tags: string[] = [];

  @f.type(ArrayBuffer).optional() //binary
  picture?: ArrayBuffer;

  @f
  type: number = 0;

  @f.enum(Plan)
  plan: Plan = Plan.DEFAULT;

  @f
  created: Date = new Date;

  @f.array(SubModel)
  children: SubModel[] = [];

  @f.map(SubModel)
  childrenMap: {[key: string]: SubModel} = {};

  constructor(
      @f.index().asName('name') //asName is required for minimized code
      public name: string
  ) {}
}

Other Variables

Const CacheJitPropertyMap

CacheJitPropertyMap: Map<PropertyCompilerSchema, any> = new Map<PropertyCompilerSchema, any>()

Const CacheValidatorInstances

CacheValidatorInstances: Map<ClassType<PropertyValidator>, PropertyValidator> = new Map<ClassType<PropertyValidator>, PropertyValidator>()

Const JITClassToPlainCache

JITClassToPlainCache: Map<any, any> = new Map<any, any>()

Const JITClassToXCache

JITClassToXCache: Map<any, Map<any, any>> = new Map<any, Map<any, any>>()

Const JITPlainToClassCache

JITPlainToClassCache: Map<any, any> = new Map<any, any>()

Const JITXToClassCache

JITXToClassCache: Map<any, Map<any, any>> = new Map<any, Map<any, any>>()

Const RegisteredEntities

RegisteredEntities: {}

Registry of all registered entity that used the @Entity('name') decorator.

Type declaration

  • [name: string]: ClassType<any>

Const cacheJitProperty

cacheJitProperty: Map<string, WeakMap<PropertySchema, any>> = new Map<string, WeakMap<PropertySchema, any>>()

Const compilerRegistry

compilerRegistry: Map<string, (setter: string, accessor: string, property: PropertyCompilerSchema, reserveVariable: () => string, context: TypeConverterCompilerContext) => string | { context: {}; template: string }> = new Map<string, TypeConverterCompiler>()

Const fRaw

fRaw: any = Field()

Const field

field: MainDecorator & FieldDecoratorResult<any> = fRaw as any

Alias for f.

Const jitFunctions

jitFunctions: WeakMap<ClassType<any>, any> = new WeakMap<ClassType<any>, any>()

Const resolvedReflectionCaches

resolvedReflectionCaches: Map<ClassType<any>, {}> = new Map<ClassType<any>, { [path: string]: PropertyCompilerSchema }>()

Const type

type: MainDecorator & FieldDecoratorResult<any> = fRaw as any

Alias for f.

Const typedArrayMap

typedArrayMap: Map<any, "string" | "number" | "boolean" | "class" | "objectId" | "uuid" | "union" | "moment" | "date" | "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "arrayBuffer" | "enum" | "any"> = new Map<any, Types>()

Const typedArrayNamesMap

typedArrayNamesMap: Map<"string" | "number" | "boolean" | "class" | "objectId" | "uuid" | "union" | "moment" | "date" | "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "arrayBuffer" | "enum" | "any", any> = new Map<Types, any>()

Const validationRegistry

validationRegistry: Map<string, (accessor: string, property: PropertyCompilerSchema, utils: { context: TypeCheckerCompilerContext; path: string; raise: (code: string, message: string) => string; reserveVariable: () => string }) => string | { context: {}; template: string }> = new Map<string, TypeCheckerCompiler>()

Decorator Functions

DatabaseName

  • DatabaseName<T>(name: string): (Anonymous function)
  • Used to define a database name for an entity. Per default marshal's database abstraction uses the default database, but you can change that using this decorator.

    Type parameters

    • T

    Parameters

    • name: string

    Returns (Anonymous function)

Entity

  • Entity<T>(name: string, collectionName?: undefined | string): (Anonymous function)
  • Used to define a entity name for an entity.

    The name is used for an internal registry, so ot should be a unique one.

    Marshal's database abstraction uses this name to generate the collection name / table name.

    Type parameters

    • T

    Parameters

    • name: string
    • Optional collectionName: undefined | string

    Returns (Anonymous function)

MultiIndex

  • MultiIndex(fields: string[], options: IndexOptions, name?: undefined | string): (Anonymous function)
  • Used to define an index on a class.

    Parameters

    • fields: string[]
    • options: IndexOptions
    • Optional name: undefined | string

    Returns (Anonymous function)

OnLoad

  • OnLoad<T>(options?: { fullLoad?: undefined | false | true }): (Anonymous function)
  • Used to define a method as callback which will be called when the object has been completely serialized. When fullLoad is true the callback is called when all references are loaded as well. This is particularly useful when you have @ParentReference() properties, which will be undefined in regular OnLoad callback.

    Example

    class User {
        @OnLoad()
        onLoad() {
            console.log('self loaded!');
        }
    
        @OnLoad({fullLoad: true})
        onFullLoad() {
            console.log('fully loaded, including parent references');
        }
    }
    

    Type parameters

    • T

    Parameters

    • Default value options: { fullLoad?: undefined | false | true } = {}
      • Optional fullLoad?: undefined | false | true

    Returns (Anonymous function)

Decorator Example one direction. ```typescript class JobConfig { @f.forward(() => Job) //forward necessary since circular dependency @ParentReference() job: Job; } class Job { @f config: JobConfig; } ``` Example circular parent-child setup. ```typescript export class PageClass { @f.uuid() id: string = uuid(); @f name: string; @f.forwardArray(() => PageClass) //forward necessary since circular dependency children: PageClass[] = []; @f.forward(() => PageClass).optional() //forward necessary since circular dependency @ParentReference() parent?: PageClass; constructor(name: string) { this.name = name; } ``` todo: Move this to @f api. Functions

ParentReference

  • Used to define a field as a reference to a parent.

    Returns FieldDecoratorResult<unknown>

Other Functions

Decorated

  • Decorated(): (Anonymous function)
  • internal

    Returns (Anonymous function)

Discriminant

  • Discriminant(): (Anonymous function)
  • internal

    Returns (Anonymous function)

EnumField

  • Used to define a field as Enum. If allowLabelsAsValue is set, you can use the enum labels as well for setting the property value using plainToClass().

    internal

    Type parameters

    • T

    Parameters

    • type: any
    • Default value allowLabelsAsValue: boolean = false

    Returns FieldDecoratorResult<unknown>

Exclude

  • Exclude(t?: "all" | string): (Anonymous function)
  • internal

    Parameters

    • Default value t: "all" | string = "all"

    Returns (Anonymous function)

Field

FieldDecoratorWrapper

  • Helper for decorators that are allowed to be placed in property declaration and constructor property declaration. We detect the name by reading the constructor' signature, which would be otherwise lost.

    Type parameters

    • T

    Parameters

    Returns FieldDecoratorResult<T>

GroupName

  • GroupName(...names: string[]): (Anonymous function)
  • internal

    Parameters

    • Rest ...names: string[]

    Returns (Anonymous function)

IDField

  • IDField(): (Anonymous function)
  • internal

    Returns (Anonymous function)

Index

  • Index(options?: IndexOptions, name?: undefined | string): (Anonymous function)
  • internal

    Parameters

    • Optional options: IndexOptions
    • Optional name: undefined | string

    Returns (Anonymous function)

MomentField

  • internal

    Type parameters

    • T

    Returns FieldDecoratorResult<unknown>

MongoIdField

  • MongoIdField(): (Anonymous function)
  • internal

    Returns (Anonymous function)

Optional

  • Optional(): (Anonymous function)
  • internal

    Returns (Anonymous function)

UUIDField

  • UUIDField(): (Anonymous function)
  • internal

    Returns (Anonymous function)

applyAndReturnPatches

  • applyAndReturnPatches<T>(item: T, patch: (item: Mutable<T>) => void): Partial<T>
  • This function enables you to track changes made to an object and return only the difference. The difference in the format of a dot-path object allows you to efficiency save or transport changes.

    Type parameters

    • T: object

    Parameters

    • item: T
    • patch: (item: Mutable<T>) => void

    Returns Partial<T>

applyPatch

  • applyPatch<T>(item: T, patch: (item: Mutable<T>) => void): T
  • Applies patches to a (readonly) object while not touching the original object and returns the cloned object while keeping unchanged reference intact.

    Allows to modify a given object partially and keeps references that weren't updated untouched. This is very useful when working with state management systems or dirty checking algorithms.

    Returns always a new object, but leaves (deep) property references intact when they haven't changed (using the patcher modifier).

    If a deep property has changed (like children.deep.title), then children, and children.deep will have a new reference/instance. children.another on other other side is not changed and would not have a new reference.

    This function is very handy when dealing with state management where you want to make sure that references only change when you really have changed either its value or some (nested) children values. Normally you have to use the spread syntax (...) to quickly create a copy of the state and re-assign only a subset of properties. Like so

    return {...state, loggedIn: true};

    This becomes quickly unused when you have a more complex state. (more complex states are generally not recommended exactly because of that reason) However, patch method enables you to work with unlimited complex stores while having a very easy and convenient way of updating only certain parts of it.

    When given item (or a children object) has constructor arguments, then it's required to annotate them using the @f decorator.

    It's allowed to pass a freezed (Object.freeze) item (and that's a main purpose of this function).

    example
    
    class Sub {
        title: string = '';
        sub: Sub = new Sub;
    }
    
    class State {
        sub: Sub = new Sub();
        otherSub: Sub = new Sub();
        title: string = '';
    }
    
    const state = new State;
    const newState = patchState(state, (state) => {
         state.sub.title = 'another-value';
    });
    state === newState //false, always the case
    state.sub === newState.sub //false, because we changed it
    state.otherSub === newState.otherSub //true, the same since unchanged
    
    const newState2 = patchState(state, (state) => {
         state.otherSub.sub.title = 'another-value';
    });
    state === newState2 //false, always the case
    state.sub === newState2.sub //true, because we haven't changed it
    state.otherSub === newState2.otherSub //false, since we deeply changed it

    Type parameters

    • T: object

    Parameters

    • item: T
    • patch: (item: Mutable<T>) => void

    Returns T

argumentClassToPlain

  • argumentClassToPlain<T>(classType: ClassType<T>, methodName: string, argument: number, value: any): any
  • Converts a argument of a method from class to plain.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • methodName: string
    • argument: number
    • value: any

    Returns any

argumentPlainToClass

  • argumentPlainToClass<T>(classType: ClassType<T>, methodName: string, argument: number, value: any): any
  • Converts an argument of a method from class to plain.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • methodName: string
    • argument: number
    • value: any

    Returns any

arrayBufferFrom

  • arrayBufferFrom(data: string, encoding?: undefined | string): ArrayBuffer
  • Same as Buffer.from() but creates a ArrayBuffer that is not shared.

    Parameters

    • data: string
    • Optional encoding: undefined | string

    Returns ArrayBuffer

arrayBufferTo

  • arrayBufferTo(arrayBuffer: ArrayBuffer, encoding?: string | "utf8" | "base64" | "ascii"): string
  • Same as Buffer.from(arrayBuffer).toString(encoding), but more in line with the current API.

    Parameters

    • arrayBuffer: ArrayBuffer
    • Optional encoding: string | "utf8" | "base64" | "ascii"

    Returns string

arrayBufferToBase64

  • arrayBufferToBase64(arrayBuffer: ArrayBuffer): string
  • Parameters

    • arrayBuffer: ArrayBuffer

    Returns string

base64ToArrayBuffer

  • base64ToArrayBuffer(base64: string): ArrayBuffer
  • Creates a new fresh ArrayBuffer with given data. Note: Regular Buffer.from(base64, 'base64) creates in Node a shared buffer, this function makes sure a copy happens and the ArrayBuffer is not shared.

    Parameters

    • base64: string

    Returns ArrayBuffer

base64ToTypedArray

  • When using Buffer.from() node is using a buffer from the buffer pool. This makes it necessary to create the given TypedArray using byteOffset and byteLength accordingly.

    Note: The created TypedArray.buffer is pointing probably to a larger Buffer. Make sure to use byteLength/byeOffset correctly or use typedArrayToArrayBuffer() if you want to use a raw ArrayBuffer that represents the actual data correctly.

    Type parameters

    • K

    Parameters

    Returns K

base64ToUint8ArrayAtoB

  • base64ToUint8ArrayAtoB(base64: string): Uint8Array
  • This function is only used in browser context, where atob is actually faster than using Buffer.from by the buffer.js library.

    Parameters

    • base64: string

    Returns Uint8Array

capitalizeFirstLetter

  • capitalizeFirstLetter(string: string): string
  • Parameters

    • string: string

    Returns string

classToPlain

  • Converts a class instance into a plain object, which can be used with JSON.stringify() to convert it into a JSON string.

    Type parameters

    • T

    Parameters

    Returns any

cloneClass

  • Clones a class instance deeply.

    Type parameters

    • T

    Parameters

    Returns T

compilerConvertClassToX

  • compilerConvertClassToX(toFormat: string): (Anonymous function)
  • Parameters

    • toFormat: string

    Returns (Anonymous function)

compilerToNumber

  • Parameters

    Returns string

compilerToString

  • Parameters

    Returns string

compilerXToClass

  • compilerXToClass(fromFormat: string): (Anonymous function)
  • Parameters

    • fromFormat: string

    Returns (Anonymous function)

compilerXToUnionClass

  • compilerXToUnionClass(fromFormat: string): (Anonymous function)
  • Parameters

    • fromFormat: string

    Returns (Anonymous function)

Const convertArrayBufferToPlain

  • convertArrayBufferToPlain(setter: any, getter: any): { template: string; context: object }
  • Parameters

    • setter: any
    • getter: any

    Returns { template: string; context: object }

Const convertToPlainUsingToJson

  • Parameters

    Returns string

Const convertTypedArrayToClass

  • convertTypedArrayToClass(setter: string, accessor: string, property: PropertyCompilerSchema): { template: string; context: object }
  • Parameters

    Returns { template: string; context: object }

    • template: string
    • context: object
      • base64ToTypedArray: base64ToTypedArray
      • typedArrayNamesMap: Map<"string" | "number" | "boolean" | "class" | "objectId" | "uuid" | "union" | "moment" | "date" | "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "arrayBuffer" | "enum" | "any", any>

Const convertTypedArrayToPlain

  • convertTypedArrayToPlain(setter: string, accessor: string, property: PropertyCompilerSchema): { template: string; context: object }
  • Parameters

    Returns { template: string; context: object }

createClassSchema

  • createClassSchema<T>(clazz?: ClassType<T>, name?: string): ClassSchema<T>
  • Creates a new ClassSchema for a given external class (you might have no write access to), which can be used to transform data for the given class. You can dynamically add properties and use then the external class as usual with plainToClass, classToPlain, etc.

    example
    class ExternalClass {
        id!: string;
        version!: number;
        lists!: number[];
    }
    
    const schema = createClassSchema(ExternalClass);
    schema.addProperty('id', f.type(String));
    schema.addProperty('version', f.type(Number));
    schema.addProperty('lists', f.array(Number));
    
    const obj = plainToClass(ExternalClass, {
        id: '23',
        version: 1,
        lists: [12, 23]
    });

    Type parameters

    • T

    Parameters

    • Optional clazz: ClassType<T>
    • Default value name: string = ""

    Returns ClassSchema<T>

createClassToXFunction

  • createClassToXFunction<T>(classType: ClassType<T>, toFormat: string | "plain"): (instance: T, options?: JitConverterOptions) => any
  • Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • toFormat: string | "plain"

    Returns (instance: T, options?: JitConverterOptions) => any

createFieldDecoratorResult

  • Type parameters

    • T

    Parameters

    • cb: (target: Object, property: PropertySchema, returnType: any, modifiedOptions: FieldOptions) => void
    • Default value givenPropertyName: string = ""
    • Default value modifier: ((target: Object, property: PropertySchema) => void)[] = []
    • Default value modifiedOptions: FieldOptions = {}
    • Default value root: boolean = false

    Returns FieldDecoratorResult<T>

createJITConverterFromPropertySchema

  • createJITConverterFromPropertySchema(fromFormat: string, toFormat: string, property: PropertySchema): (value: any, parents?: any[]) => any
  • Creates a new JIT compiled function to convert given property schema. Deep paths are not allowed.

    Parameters

    Returns (value: any, parents?: any[]) => any

      • (value: any, parents?: any[]): any
      • Parameters

        • value: any
        • Optional parents: any[]

        Returns any

createXToClassFunction

  • createXToClassFunction<T>(classType: ClassType<T>, fromTarget: string | "plain"): (data: {}, options?: JitConverterOptions, parents?: any[], state?: ToClassState) => T

executeCheckerCompiler

executeCompiler

forwardRef

  • Allows to refer to references which are not yet defined.

    For instance, if you reference a circular dependency or a not yet defined variable.

    class User {
        @f.forward(() => Config)
        config: Config;
    
        @f.forwardArray(() => Config)
        configArray: Config[] = [];
    
        @f.forwardMap(() => Config)
        configMap: {[k: string]: Config} = {};
    

    Type parameters

    • T

    Parameters

    Returns ForwardedRef<T>

getClassSchema

  • getClassSchema<T>(classTypeIn: ClassType<T> | Object): ClassSchema<T>
  • Returns meta information / schema about given entity class.

    Type parameters

    • T

    Parameters

    • classTypeIn: ClassType<T> | Object

    Returns ClassSchema<T>

getClassTypeFromInstance

  • getClassTypeFromInstance<T>(target: T): ClassType<T>
  • Returns the ClassType for a given instance.

    Type parameters

    • T

    Parameters

    • target: T

    Returns ClassType<T>

getDataCheckerJS

getDataConverterJS

getEntityName

  • getEntityName<T>(classType: ClassType<T>): string
  • Type parameters

    • T

    Parameters

    • classType: ClassType<T>

    Returns string

getParentResolverJS

  • getParentResolverJS<T>(classType: ClassType<T>, setter: string, property: PropertySchema, context: Map<string, any>): string
  • Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • setter: string
    • property: PropertySchema
    • context: Map<string, any>

    Returns string

handleCustomValidator

isArray

  • isArray(v: any): v is Array<any>
  • Parameters

    • v: any

    Returns v is Array<any>

isClassInstance

  • isClassInstance(target: any): boolean
  • Returns true when target is a class instance.

    Parameters

    • target: any

    Returns boolean

isGroupAllowed

  • Parameters

    Returns boolean

isPropertyValidator

  • isPropertyValidator(object: any): object is ClassType<PropertyValidator>
  • Parameters

    • object: any

    Returns object is ClassType<PropertyValidator>

isRegisteredEntity

  • isRegisteredEntity<T>(classType: ClassType<T>): boolean
  • Returns true if given class has an @Entity() or @f defined, and thus became a Marshal entity.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>

    Returns boolean

isTypedArray

  • isTypedArray(type: Types): boolean
  • Parameters

    Returns boolean

jitClassToPlain

  • jitClassToPlain<T>(classType: ClassType<T>, instance: T, options?: JitConverterOptions): Partial<T>
  • Type parameters

    • T

    Parameters

    Returns Partial<T>

jitPartial

  • jitPartial<T, K>(fromFormat: string, toFormat: string, classType: ClassType<T>, partial: {}, options?: JitConverterOptions): Partial<{}>
  • Type parameters

    • T

    • K: keyof T

    Parameters

    • fromFormat: string
    • toFormat: string
    • classType: ClassType<T>
    • partial: {}
      • [name: string]: any
    • Default value options: JitConverterOptions = {}

    Returns Partial<{}>

jitPartialClassToPlain

  • jitPartialClassToPlain<T, K>(classType: ClassType<T>, partial: {}, options?: JitConverterOptions): Partial<{}>
  • Type parameters

    • T

    • K: keyof T

    Parameters

    • classType: ClassType<T>
    • partial: {}
      • [name: string]: any
    • Default value options: JitConverterOptions = {}

    Returns Partial<{}>

jitPartialPlainToClass

  • jitPartialPlainToClass<T, K>(classType: ClassType<T>, partial: {}, options?: JitConverterOptions): Partial<{}>
  • Type parameters

    • T

    • K: keyof T

    Parameters

    • classType: ClassType<T>
    • partial: {}
      • [name: string]: any
    • Default value options: JitConverterOptions = {}

    Returns Partial<{}>

jitPlainToClass

  • Type parameters

    • T

    Parameters

    Returns T

jitValidate

jitValidatePartial

  • Type parameters

    • T

    • K: keyof T

    Parameters

    • classType: ClassType<T>
    • partial: {}
      • [name: string]: any
    • Optional path: undefined | string
    • Optional errors: ValidationError[]

    Returns ValidationError[]

jitValidateProperty

methodResultClassToPlain

  • methodResultClassToPlain<T>(classType: ClassType<T>, methodName: string, value: any): any
  • Converts a result type of a method from class to plain.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • methodName: string
    • value: any

    Returns any

methodResultPlainToClass

  • methodResultPlainToClass<T>(classType: ClassType<T>, methodName: string, value: any): any
  • Converts a result type of a method from class to plain.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • methodName: string
    • value: any

    Returns any

Let moment

  • moment(): never
  • Returns never

nodeBufferToArrayBuffer

  • nodeBufferToArrayBuffer<K>(buf: Buffer): ArrayBuffer
  • When using Buffer.from() node is using a buffer from the buffer pool. This makes it necessary to create the a new ArrayType using slice to make a copy.

    This makes a copy.

    Type parameters

    • K

    Parameters

    • buf: Buffer

    Returns ArrayBuffer

nodeBufferToTypedArray

  • Type parameters

    • K

    Parameters

    Returns K

partialClassToPlain

  • partialClassToPlain<T, K>(classType: ClassType<T>, target: {}, options?: JitConverterOptions): Partial<{}>
  • Takes a object with partial class fields defined of classType and converts only them into the plain variant.

    Returns a new regular object again.

    Type parameters

    • T

    • K: keyof T

    Parameters

    • classType: ClassType<T>
    • target: {}
      • [path: string]: any
    • Default value options: JitConverterOptions = {}

    Returns Partial<{}>

partialPlainToClass

  • partialPlainToClass<T, K>(classType: ClassType<T>, target: {}, options?: JitConverterOptions): Partial<{}>
  • Takes a regular object with partial fields defined of classType and converts only them into the class variant.

    Returns a new regular object again.

    Type parameters

    • T

    • K: keyof T

    Parameters

    • classType: ClassType<T>
    • target: {}
      • [path: string]: any
    • Default value options: JitConverterOptions = {}

    Returns Partial<{}>

plainToClass

  • Take a regular object literal and returns an instance of classType. Missing data is either replaced by the default value of that property or undefined.

    This method does not validate the given data. Use either validatedPlainToClass to validate beforehand or use validate on your newly created instance.

    const entity = plainToClass(MyEntity, {field1: 'value'});
    entity instanceof MyEntity; //true

    Type parameters

    • T

    Parameters

    Returns T

propertyClassToPlain

  • propertyClassToPlain<T>(classType: ClassType<T>, propertyName: string, propertyValue: any, propertySchema?: PropertySchema): any
  • Converts a single property value.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • propertyName: string
    • propertyValue: any
    • Optional propertySchema: PropertySchema

    Returns any

registerCheckerCompiler

  • Parameters

    Returns void

registerConverterCompiler

  • Registers a new compiler template for a certain type in certain direction (plain to class, class to plain for example).

    Note: Don't handle isArray/isMap/isPartial or isOptional at property as those are already handled before your compiler code is called. Focus on marshalling the given type as fast and clear as possible. The value you can access via accessor is at this stage never undefined and never null.

    Note: When you come from class to x (registerConverterCompile('class', x)) then values additionally are guaranteed to have certain value types since the TS system enforces it. Marshal plainToClass made that sure as well. If a user overwrites with as any its not our business to convert them implicitly.

    Warning: Context is shared across types, so make sure either your assigned names are unique or generate new variable name using reserveVariable.

    INTERNAL WARNING: However, coming from plain to x the property values usually come from user input which makes it necessary to check the type and convert it if necessary. This is extremely important to not introduce security issues. As third-party integration you should however not handle fromFormat='plain', as this is made in the core. Marshaling from plain to your target platform is made by calling first plainToClass() and then classToX(), Marshal is fast enough to buy this convenience (of not having to declare too many compiler templates).

    Parameters

    Returns void

require

  • require(moduleName: string): any
  • Parameters

    • moduleName: string

    Returns any

reserveVariable

  • Parameters

    Returns string

resolveClassTypeOrForward

  • resolveClassTypeOrForward(type: ClassType<any> | ForwardRefFn<ClassType<any>>): ClassType<any>
  • Parameters

    Returns ClassType<any>

resolvePropertyCompilerSchema

  • This resolves the PropertyCompilerSchema for a property path.

    A property path can be a deep path, separated with dots. This function makes sure to return the correct PropertyCompilerSchema so that a correct compiler can be built to convert this type.

    Type parameters

    • T

    Parameters

    Returns PropertyCompilerSchema

shallowCloneObject

  • shallowCloneObject<T>(item: T): T
  • Shallow clones an object.

    Supports constructor arguments, but requires to annotate them using @f decorator.

    Type parameters

    • T: object

    Parameters

    • item: T

    Returns T

typedArrayToBase64

  • typedArrayToBase64(typedArray: TypedArray): string
  • Parameters

    Returns string

typedArrayToBuffer

  • typedArrayToBuffer<K>(typedArray: TypedArray): Buffer
  • In node environment the TypedArray.buffer is probably a larger buffer from the buffer pool. This makes it necessary to create a Buffer with offset & length so that it accurately represents the given TypedArray.

    Type parameters

    • K

    Parameters

    Returns Buffer

uuid

  • uuid(): string
  • Returns string

validate

  • validate<T>(classType: ClassType<T>, item: {} | T, path?: undefined | string): ValidationError[]
  • Validates a object or class instance and returns all errors. Returns an empty array if not errors found and validation succeeded.

    example
    validate(SimpleModel, {id: false});

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • item: {} | T
    • Optional path: undefined | string

    Returns ValidationError[]

validateMethodArgs

  • validateMethodArgs<T>(classType: ClassType<T>, methodName: string, args: any[]): ValidationError[]
  • Validates a set of method arguments and returns the number of errors found.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • methodName: string
    • args: any[]

    Returns ValidationError[]

validatedPlainToClass

  • validatedPlainToClass<T>(classType: ClassType<T>, data: object, options?: JitConverterOptions): T
  • Same as [plainToClass] but with validation before creating the class instance.

    try {
        const entity = await validatedPlainToClass(MyEntity, {field1: 'value'});
        entity instanceof MyEntity; //true
    } catch (error) {
        if (error instanceof ValidationFailed) {
            //handle that case.
        }
    }

    Type parameters

    • T

    Parameters

    Returns T

validates

  • validates<T>(classType: ClassType<T>, item: {}): item is T
  • A type guarded way of using Marshal.

    Note: Methods are not type guarded.

    example
    if (validates(SimpleMode, data)) {
        //data is now typeof SimpleMode
    }

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • item: {}
      • [name: string]: any

    Returns item is T

validatesFactory

  • validatesFactory<T>(classType: ClassType<T>): (item: {}) => item is T
  • A type guarded way of using Marshal as factory for faster access.

    Note: Methods are not type guarded.

    example
    const simpleModelValidates = validatesFactory(SimpleMode);
    if (simpleModelValidates(data)) {
        //data is now typeof SimpleMode
    }

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>

    Returns (item: {}) => item is T

      • (item: {}): item is T
      • Parameters

        • item: {}
          • [name: string]: any

        Returns item is T

Object literals

Const MarshalGlobal

MarshalGlobal: object

unpopulatedCheckActive

unpopulatedCheckActive: boolean = true

Generated using TypeDoc