$ open source · GPL-3.0 — need a commercial license? imqueue.com →

DynamicView() function

Declares a model to be a view whose definition is parameterised per query.

Signature:

export declare function DynamicView(options: IDynamicViewDefineOptions): (target: any) => void;

Parameters

Parameter

Type

Description

options

IDynamicViewDefineOptions

Model options carrying the definition and the parameter defaults.

Returns:

(target: any) => void

A class decorator.

Exceptions

TypeError when the definition is missing or blank, or when it names a placeholder that viewParams does not.

Remarks

Everything View does, plus placeholders. The definition may carry @{name} markers, every finder accepts viewParams to fill them, and the select-query generator substitutes them and splices the resulting statement into the query — as the FROM target, or as a joined subquery when the view is reached through an include. One model then serves a family of views that differ only by a constant, which is the alternative to defining one view per variant in a migration.

Every placeholder must have a default in viewParams. That is checked while the class is being defined, so a missing one is an error at import rather than a malformed statement at query time.

Values are escaped, so a parameter can carry a caller's input. Anything that is not a number or a string becomes NULL.

Example

@DynamicView({
    viewDefinition: `
        CREATE OR REPLACE VIEW "ProductRevenue" AS
        SELECT "productId" AS "id", SUM("payment") AS "revenue"
          FROM "Order"
         WHERE "currency" = @{currency}
         GROUP BY "productId"
    `,
    viewParams: { currency: 'USD' },
    freezeTableName: true,
    timestamps: false,
})
export class ProductRevenue extends BaseModel<ProductRevenue> {
    @PrimaryKey
    @Column(DataType.BIGINT)
    declare public id: number;
}

// the same model, read in another currency
const rows = await ProductRevenue.findAll({
    viewParams: { currency: 'EUR' },
});