Thursday 22 February 2018

Knex/Express: how to log query with data from request?

I am new to Node and not quite sure how to do this. I need to save to the database what query was ran by what user. I am able to save just the query itself by listening to the response-query on the single Knex object i.e.knex.on('query-response', async (response, obj, builder) => { const sql = builder.toString(); await saveToDatabase(sql); }); Then, any query that I run with Knex gets persisted to the database. All that works.However, now I need to save the user id as well. The user id is on the req object in my Express pipeline. How do I get it into my code that saves what query was ran by the use? I had originally tried creating an Express middleware that sets up the listener on the Knex object and then removes it once the request has completed, but I think that has concurrency issues.Is there any general (or even specific) advice for how to handle this problem? I've been doing .Net for a long time now and ASP.NET mostly solves this kind of issue for me. I also think it wouldn't be a problem if the Knex object wasn't a singleton but the docs sayInitializing the library should normally only ever happen once in your application, as it creates a connection pool for the current database, you should use the instance returned from the initialize call throughout your library.

Submitted February 23, 2018 at 02:10AM by clockdivide55

No comments:

Post a Comment