Как управлять валидацией и необработанными значениями в Objection.js

У меня есть эта модель в 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
    }

Мне нужно вставить время базы данных в timestamp колонка. Когда возражение выполняет проверку, значение timestamp это пример функции Raw Knex:

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

// continues

Поэтому, когда проверка выполняется, возвращается ошибка, поскольку она не является строкой:

Validation error: "timestamp" should be a string

Есть ли способ использовать время базы данных и сохранить проверку?

1 ответ

Решение

Вы должны связать конструктор запросов с помощью ".then()", чтобы получить результат запроса или использовать async/await. Это может сработать:

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

или же:

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

https://knexjs.org/

Другие вопросы по тегам