0

Hey everyone i have the following code that retrieves data from cloud, then i need to save it to a database. I did it using Knex to make a seed file, and also using a regular function, but i need to do it using transactions with Knex.

Here is what i did :

function addPatient(){
  return knex.transaction((t) => {
    return knex('patients').insert({
      uid: patient.uid,
      first_name: patient.first_name,
      last_name: patient.last_name,
      birth_date: patient.birth_date,
      code: patient.code,
      birthsex: patient.birthsex,
    })
  }).then(t.commit)
  .catch(function(e) {
    t.rollback();
    throw e;
  })
}

Although sometimes i replaced the json by a variable object that gets all the data.

And i imported knex as following :

const knex = require(path.join(__dirname, 'knexfile.js'));

What intrigues me is i get this error : knex.transaction is not a function, can anyone please hint or help or point to me where i am wrong ?

Thank you

Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18
Montasser
  • 77
  • 5
  • PS : i have also tried all the knex.transaction codes that are in knexjs.org, i guess it is on how or when i call and declare my function, but i can't understand where is the error. Thanks – Montasser Aug 19 '20 at 08:40
  • You're chaining `t.commit` and `t.rollback` to the wrong places. Those should be chained to `insert`. `t` is not defined anywhere you attempt to use it. `t` is only available within the `knex.transaction` callback. – nicholaswmin Aug 20 '20 at 08:36
  • @nicholaswmin thanks a lot for the answer, it is true i did not chain correctly the t.commit or t.rollback to the insert, yet i got the code from the official website of knexjs.org, i couldn't see they declaring t, so i don't know if i only have to put a const t, or should it be done in another way. Thanks – Montasser Aug 20 '20 at 09:45
  • Here's an example using `async/await` instead of Promises: https://stackoverflow.com/a/63053884/1814486 – nicholaswmin Aug 20 '20 at 09:51
  • @nicholaswmin thanks a lot, yet it gives me that it needs to be in an async function, and it doesn't use knex, i tried using a synchronous version i found here :https://stackoverflow.com/questions/22957032/knex-transaction-with-promises but i didn't save in database. Knex is necessary to use in my case between – Montasser Aug 20 '20 at 14:30
  • It's using knex it's just defined as `db` in that example I've sent you. – nicholaswmin Aug 20 '20 at 15:19

0 Answers0