Search code examples
javascriptnode.jsknex.jsobjection.js

How to manage Validation vs raw values in Objection.js


I have this model in Objection.js:

class UserAccess extends Model {
    static get tableName() {
        return 'user_access'
    }

    static get jsonSchema() {
        return {
            type: 'object',
            properties: {
                id: {
                    type: 'integer'
                },
                user_id: {
                    type: 'integer'
                }
                timestamp: {
                    type: 'string',
                    format: 'date-time'
                },
            },
            additionalProperties: false
        }
    }

    $beforeInsert() {
        this.timestamp = this.$knex().raw('now()')
    }

    static async insert(data) {
        const result = await this.query().insert(data)
        return result.id
    }

I need to insert the database time in timestamp column. When Objection executes the validation, the value of timestamp is an intance of Raw Knex Function:

Raw {
  client:
   Client_MySQL2 {
     config: { client: 'mysql2', connection: [Object] },
     connectionSettings:
      { user: '',
        password: '',
        host: '',
        database: '' },
     driver:
      { createConnection: [Function],
        connect: [Function],

// continues

So when validation is executed, an error is returned, since it isnt a string:

Validation error: "timestamp" should be a string

Is there any way to use the database time and keep the validation?


Solution

  • You have to chain the query builder with a ".then()" to get the query result or use async/await. This might work:

    async $beforeInsert() {
        this.timestamp = await this.$knex().raw('now()')
    }
    

    or:

    $beforeInsert() {
       this.timestamp = this.$knex().raw('now()').then(function(result) {
          console.log(result)
       })
    }
    

    https://knexjs.org/#Interfaces