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

View() function

Declares a model to be a database view rather than a table.

Signature:

export declare function View(options: IViewDefineOptions | string): (target: any) => void;

Parameters

Parameter

Type

Description

options

IViewDefineOptions | string

The definition SQL alone, or model options carrying it.

Returns:

(target: any) => void

A class decorator.

Exceptions

TypeError when there is no definition, or it is blank. The string form used to skip that check, and an options object without the property threw an unhelpful error from reading it.

Remarks

Does for a view what Table does for a table, and sets the flag the rest of the package keys off: the model is skipped by the table sync, created and dropped with view statements, and has its numeric columns re-cast after every finder, since a view returns them as strings.

Two ordinary model options matter more here than they look. freezeTableName stops sequelize pluralising the model name, which has to match the name inside the definition. And timestamps: false stops it selecting createdAt and updatedAt, which a view has no reason to have. A view model may also extend another model instead of BaseModel, which is the shortest way to reuse a table's column declarations for a view over the same columns.

Declared columns are a subset of what the view selects: anything the view returns and the model does not declare is simply not mapped.

Example

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

    @Column(DataType.DECIMAL(12, 2))
    declare public revenue: number;
}