Skip to content

patch() breaks if useDefineForClassFields is enabled in tsconfig.json #2105

@sloonz

Description

@sloonz

If the model is compiled with useDefineForClassField set to true in tsconfig.json, then the patch() method fails. Simplest reproduction :

const Model = require('objection').Model;
const Knex = require('knex');

async function main() {
  await createSchema();
  await Person.query().insertGraph({
    firstName: 'Jennifer',
    lastName: 'Lawrence',
  });

  const jennifer = await Person.query()
    .findOne({ firstName: 'Jennifer' });
  console.error(jennifer);
  await jennifer.$query().patch({ lastName: 'Lopez' });
  console.error(jennifer);
}

const knex = Knex({
  client: 'sqlite3',
  useNullAsDefault: true,
  debug: false,
  connection: {
    filename: ':memory:'
  }
});

Model.knex(knex);

class Person extends Model {
  static tableName = 'Person';
  id!: number;
  firstName!: string;
  lastName!: string;
}

async function createSchema() {
  await knex.schema
    .dropTableIfExists('Person');

  await knex.schema
    .createTable('Person', (table: any) => {
      table.increments('id').primary();
      table.string('firstName');
      table.string('lastName');
    });
}

main()
  .then(() => knex.destroy())
  .catch(err => {
    console.error(err);
    return knex.destroy();
  });

Expected output :

Person { id: 1, firstName: 'Jennifer', lastName: 'Lawrence' }
Person { id: 1, firstName: 'Jennifer', lastName: 'Lopez' }

Actual output :

Person { id: 1, firstName: 'Jennifer', lastName: 'Lawrence' }
Person { id: undefined, firstName: undefined, lastName: 'Lopez' }

This is because {...new Person()} has a different behavior depending on useDefineForClassFields : if true, this returns {id: undefined, firstName: undefined, lastName: undefined} ; if false, this returns {}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions