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

Type aliases

FieldTypes

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

ForwardRefFn

ForwardRefFn: function

Type declaration

    • (): T
    • Returns T

IndexOptions

IndexOptions: Partial<object>

ResolvedReflectionCaches

ResolvedReflectionCaches: object

Type declaration

  • [path: string]: ResolvedReflection

Types

Types: "objectId" | "uuid" | "binary" | "class" | "date" | "string" | "boolean" | "number" | "enum" | "any"

Variables

Const RegisteredEntities

RegisteredEntities: object

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

Type declaration

  • [name: string]: ClassType<any>

Const cache

cache: Map<Object, Map<string, any>> = new Map<Object, Map<string, any>>()

Const objectIdValidation

objectIdValidation: RegExp = new RegExp(/^[a-fA-F0-9]{24}$/)

Const parentReferencesCache

parentReferencesCache: Map<ClassType<any>, object> = new Map<ClassType<any>, { [propertyName: string]: any }>()

Const propertyNamesCache

propertyNamesCache: Map<ClassType<any>, string[]> = new Map<ClassType<any>, string[]>()

Const resolvedReflectionCaches

resolvedReflectionCaches: Map<ClassType<any>, object> = new Map<ClassType<any>, ResolvedReflectionCaches>()

Const uuidValidation

uuidValidation: RegExp = new RegExp(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)

Functions

AddValidator

  • AddValidator<T>(validator: ClassType<T>): (Anonymous function)
  • Decorator to add a custom validator class.

    example
    import {PropertyValidator} from '@marcj/marshal';
    
    class MyCustomValidator implements PropertyValidator {
         async validate<T>(value: any, target: ClassType<T>, propertyName: string): PropertyValidatorError | void {
             if (value.length > 10) {
                 return new PropertyValidatorError('too_long', 'Too long :()');
             }
         };
    }
    
    class Entity {
        @Field()
        @AddValidator(MyCustomValidator)
        name: string;
    }
    
    category

    Decorator

    Type parameters

    Parameters

    • validator: ClassType<T>

    Returns (Anonymous function)

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.

    category

    Decorator

    Type parameters

    • T

    Parameters

    • name: string

    Returns (Anonymous function)

Decorated

  • Decorated(): function
  • Used to define a field as decorated. This is necessary if you want to wrap a field value in the class instance using a own class, like for example for Array manipulations, but keep the JSON and Database value as primitive as possible.

    Only one field per class can be the decorated one.

    category

    Decorator

    Example

    export class PageCollection {
        @Field(() => PageClass)
        @Decorated()
        private readonly pages: PageClass[] = [];
    
        constructor(pages: PageClass[] = []) {
            this.pages = pages;
        }
    
        public count(): number {
            return this.pages.length;
        }
    
        public add(name: string): number {
            return this.pages.push(new PageClass(name));
        }
    }
    
    export class PageClass {
        @UUIDType()
        id: string = uuid();
    
        @Field()
        name: string;
    
        @ClassCircular(() => PageCollection)
        children: PageCollection = new PageCollection;
    
        constructor(name: string) {
            this.name = name;
        }
    }

    If you use classToPlain(PageClass, ...) or classToMongo(PageClass, ...) the field value of children will be the type of PageCollection.pages (always the field where @Decorated() is applied to), here a array of PagesClass PageClass[].

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

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.

    category

    Decorator

    Type parameters

    • T

    Parameters

    • name: string
    • Optional collectionName: undefined | string

    Returns (Anonymous function)

EnumField

  • EnumField<T>(type: any, allowLabelsAsValue?: boolean): function
  • 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().

    category

    Decorator

    Type parameters

    • T

    Parameters

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

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

Exclude

  • Exclude(): function
  • Used to define a field as excluded when serialized to Mongo or JSON. PlainToClass or mongoToClass is not effected by this.

    category

    Decorator

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

ExcludeToMongo

  • ExcludeToMongo(): function
  • Used to define a field as excluded when serialized to Mongo. PlainToClass or mongoToClass is not effected by this.

    category

    Decorator

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

ExcludeToPlain

  • ExcludeToPlain(): function
  • Used to define a field as excluded when serialized to JSON. PlainToClass or mongoToClass is not effected by this.

    category

    Decorator

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

Field

  • Decorator to define a field for an entity.

    class User {
        @Field()
        @Optional()
        num?: number;
    
        @Field()
        @Optional()
        birthdate?: Date;
    
        @Field()
        @Optional()
        yes?: Boolean;
    
        @Field([String])
        tags: string[] = [];
    
        @Field({String})
        flatStringConfigs: {[name: string]: String} = {}};
    
        @FieldAny({})
        flatConfig: {[name: string]: any} = {}};
    
        @Field(MyClass)
        config: MyClass = new wMyClass;
    
        @Field([MyClass])
        configArray: MyClass[] = []];
    
        @Field({MyClass})
        configMap: {[name: string]: MyClass} = {}};
    
        constrcutor(
            @Field()
            @Index({unique: true})
            public name: string
        ) {}
    }
    category

    Decorator

    Parameters

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

FieldAndClassDecoratorWrapper

  • FieldAndClassDecoratorWrapper(cb: function): function
  • Parameters

    • cb: function
        • (target: Object, property?: undefined | string, returnType?: any): void
        • Parameters

          • target: Object
          • Optional property: undefined | string
          • Optional returnType: any

          Returns void

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

FieldAny

  • FieldAny(type?: __type | Array<any>): function
  • Same as @Field() but defines type as 'any'. With type any no transformation is applied.

    class User {
        @FieldAny()
        config: any;
    
        @FieldAny([])
        configs: any[];
    
        @FieldAny({})
        configMap: {[name: string]: any};
    }
    
    category

    Decorator

    Parameters

    • Optional type: __type | Array<any>

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

FieldArray

  • Same as @Field(T) but defines the field as map of type T.

    class User {
        @FieldArray(String)
        tags: string[];
    
        @Field([String])
        tags: string[];
    }
    category

    Decorator

    Parameters

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

FieldDecoratorWrapper

  • FieldDecoratorWrapper(cb: function): function
  • 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.

    Parameters

    • cb: function
        • (target: Object, property: string, returnType?: any): void
        • Parameters

          • target: Object
          • property: string
          • Optional returnType: any

          Returns void

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

FieldMap

  • Same as @Field(T) but defines the field as array of type T. This is the same as @Field({T}).

    Use this method if you reference a circular dependency class, e.g.

    
    class User {
        @FieldMap(() => MyConfig)
        config: {[k: string]: MyConfig};
    }
    class User {
        @FieldMap(String)
        tags: {[k: string]: string};
    
        @Field({String})
        tags: {[k: string]: string};
    }
    category

    Decorator

    Parameters

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

IDField

  • IDField(): function
  • Used to define a field as a reference to an ID. This is important if you interact with the database abstraction.

    Only one field can be the ID.

    category

    Decorator

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

Index

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

    category

    Decorator

    Parameters

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

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

InlineValidator

  • InlineValidator<T>(cb: function): (Anonymous function)
  • Decorator to add a custom inline validator.

    example
    class Entity {
        @Field()
        @InlineValidator(async (value: any) => {
             if (value.length > 10) {
                 return new PropertyValidatorError('too_long', 'Too long :()');
             }
        }))
        name: string;
    }
    category

    Decorator

    Type parameters

    Parameters

    Returns (Anonymous function)

MongoIdField

  • MongoIdField(): function
  • Used to define a field as ObjectId. This decorator is necessary if you want to use Mongo's _id.

    class Page {
        @MongoIdField()
        referenceToSomething?: string;
    
        constructor(
            @IdType()
            @MongoIdField()
            public readonly _id: string
        ) {
    
        }
    }
    category

    Decorator

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

OnLoad

  • OnLoad<T>(options?: object): (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');
        }
    }
    
    category

    Decorator

    Type parameters

    • T

    Parameters

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

    Returns (Anonymous function)

Optional

  • Optional(): (Anonymous function)
  • Used to mark a field as optional. The validation requires field values per default, this makes it optional.

    category

    Decorator

    Returns (Anonymous function)

ParentReference

  • ParentReference(): function
  • Used to define a field as a reference to a parent.

    category

    Decorator

    Example one direction.

    class JobConfig {
        @Type(() => Job) //necessary since circular dependency
        @ParentReference()
        job: Job;
    
    }
    
    class Job {
        @Field()
        config: JobConfig;
    }

    Example circular parent-child setup.

    export class PageClass {
        @UUIDType()
        id: string = uuid();
    
        @Field()
        name: string;
    
        @Field(() => PageClass)
        @ArrayType()
        children: Page[] = [];
    
        @Field(() => PageClass)
        @ParentReference()
        @Optional()
        parent?: PageClass;
    
        constructor(name: string) {
            this.name = name;
        }

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

UUIDField

  • UUIDField(): function
  • Used to define a field as UUID (v4).

    category

    Decorator

    Returns function

      • (target: Object, property?: undefined | string, parameterIndexOrDescriptor?: any): void
      • Parameters

        • target: Object
        • Optional property: undefined | string
        • Optional parameterIndexOrDescriptor: any

        Returns void

addValidator

  • addValidator<T>(target: Object, property: string, validator: ClassType<T>): void
  • Type parameters

    Parameters

    • target: Object
    • property: string
    • validator: ClassType<T>

    Returns void

classToPlain

  • classToPlain<T>(classType: ClassType<T>, target: T): any
  • Converts a class instance into a plain object, which an be used with JSON.stringify() to convert it into a JSON string.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>
    • target: T

    Returns any

cloneClass

  • cloneClass<T>(target: T, parents?: any[]): T
  • Clones a class instance deeply.

    Type parameters

    • T

    Parameters

    • target: T
    • Optional parents: any[]

    Returns T

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 {
        @Field(forwardRef(() => Config)
        config: Config;
    
    
        @Field([forwardRef(() => Config])
        configArray: Config[] = [];
    
        @FieldArray(forwardRef(() => Config)
        configArray: Config[] = [];
    
    
        @FieldMap(forwardRef(() => Config)
        configMap: {[k: string]: Config} = {};
    
        @Field({forwardRef(() => Config})
        configMap: {[k: string]: Config} = {};
    }
    

    Type parameters

    • T

    Parameters

    Returns ForwardedRef<T>

getEntityName

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

    • T

    Parameters

    • classType: ClassType<T>

    Returns string

getEntitySchema

  • Returns meta information / schema about given entity class.

    Type parameters

    • T

    Parameters

    • classType: ClassType<T>

    Returns EntitySchema

partialClassToPlain

  • partialClassToPlain<T, K>(classType: ClassType<T>, target: object): Partial<object>
  • 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: object
      • [path: string]: any

    Returns Partial<object>

partialPlainToClass

  • partialPlainToClass<T, K>(classType: ClassType<T>, target: object, parents?: any[]): Partial<object>
  • 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: object
      • [path: string]: any
    • Optional parents: any[]

    Returns Partial<object>

plainToClass

  • plainToClass<T>(classType: ClassType<T>, data: object, parents?: any[]): T
  • 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

    • classType: ClassType<T>
    • data: object
    • Optional parents: any[]

    Returns T

uuid

  • uuid(): string
  • Returns string

validate

  • validate<T>(classType: ClassType<T>, item: object | T, path?: undefined | string): ValidationError[]
  • Validates a object or class instance and returns all errors.

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

    Type parameters

    • T

    Parameters

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

    Returns ValidationError[]

validatedPlainToClass

  • validatedPlainToClass<T>(classType: ClassType<T>, data: object, parents?: any[]): 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

    • classType: ClassType<T>
    • data: object
    • Optional parents: any[]

    Returns T

Generated using TypeDoc