Skip to content

Timestamps in a base class #110

@anyong

Description

@anyong

My model classes all extend from a base class. I would like a simple static timestamps = true; to automatically add the timestamps to created_at and updated_at as appropriate for insert and update queries, and also to add created_at and updated_at to jsonSchema so that it passes validation. I can't get it working. Currently I have something like this:

class BaseModel extends objection.Model {
    $beforeValidate (jsonSchema, json, opt) {
        if (this.constructor.timestamps) {
            jsonSchema.properties.created_at = {type: 'string'};
            jsonSchema.properties.updated_at = {type: 'string'};
        }

        return jsonSchema;
    }

    $beforeInsert () {
        if (this.constructor.timestamps) {
            const now = new Date().toISOString();
            this.created_at = now;
            this.updated_at = now;
        }
    }

    $beforeUpdate () {
        if (this.constructor.timestamps) {
            const now = new Date().toISOString();
            this.updated_at = now;
        }
    }
}

class MyModel extends BaseModel {
    static timestamps = true;
}

I've tracked down the problem to toKnexInput, which calls $toDatabaseJson, which is looking at the original jsonSchema as opposed to the modified version returned from beforeValidate. What's the point of being able to output a new jsonSchema from $beforeValidate if $toDatabaseJson (and presumably other methods) ignore it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions