Take the following INSERT query. Using knex
(JS) just for abstractions
function addUser() {
return knex.insert({username: 'newuser'}).into('users')
}
Now, by default, knex
will internally create a connection to execute this query. But there may be situations where I want to reuse a connection (e.g: transaction) instead of using a connection pool.
How would you write this function in that case? One option I can think of is
function addUser(connection) {
const conn = connection? connection || knex;
return conn.insert({username: 'newuser'}).into('users')
}
If we don't pass any connection object, it will use the connection pool by default. This works, but this feels ugly. Is there any other functional pattern that you know of that can take care of this issue?
1 Answer 1
One function, multiple signatures
There is no other pattern, you either pass a connection or you don't.
However JS is a very expressive language so there are many ways to achieve the same result.
Using default parameters and the best option.
function addUser(con = knex) {
return con.insert({username: 'newuser'}).into('users');
}
Using ?? (Nullish coalescing operator)
function addUser(con) {
return (con ?? knex).insert({username: 'newuser'}).into('users');
}
Using ? (Conditional operator)
function addUser(con) {
return (con ? con : knex).insert({username: 'newuser'}).into('users');
}
Or the same again as arrow functions
const addUser = (con = knex) => con.insert({username: 'newuser'}).into('users');
const addUser = con => (con ?? knex).insert({username: 'newuser'}).into('users');
const addUser = con => (con ? con : knex).insert({username: 'newuser'}).into('users');