herbsjs / herbs2knex

Create repositories using Knex to retrieve and store Entities
Other
7 stars 13 forks source link

herbs2knex dont works for singleton #17

Closed italojs closed 3 years ago

italojs commented 3 years ago

I noted when I use the same instance for multiple actions on database, some queries just get in bug after first database operation.

Here I wrote an demo that I did an insert, findbyid and update but the update method throw an exception

TypeError: Cannot read property 'id' of undefined
at Object.get [as id] (/Users/italojs/dev/herbjs/herbs2knex/xp/node_modules/herbs2knex/src/dataMapper.js:121:48)
at Function.fromJSON (/Users/italojs/dev/herbjs/herbs2knex/xp/node_modules/gotu/src/baseEntity.js:119:96)
at DataMapper.toEntity (/Users/italojs/dev/herbjs/herbs2knex/xp/node_modules/herbs2knex/src/dataMapper.js:19:28)
at UserRepository.update (/Users/italojs/dev/herbjs/herbs2knex/xp/node_modules/herbs2knex/src/repository.js:164:28)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async main (/Users/italojs/dev/herbjs/herbs2knex/xp/index.js:48:21)

I believe it can be an bug. To solve it, basically we can

  1. Removes the singleton runner into Repository
  2. Creates a new Knex Builder for each query like:

    
    [...]
    async insert(entityInstance) {
    [...]
    const ret = await this.knex(this.tableQualifiedName) // here
      .returning(fields)
      .insert(payload)
    [...]
    }
    
    async update(entityInstance) {
    [...]
    const ret = await this.knex(this.tableQualifiedName) // here
      .where(tableIDs[0], entityInstance[tableIDs[0]])
      .returning(fields)
      .update(payload)
    
    [...]
    }

[...]

jhomarolo commented 3 years ago

@italojs , thank you for your contribution.

I merged and updated the knex version. Could you send a PR with the updated version in the todo-list?