0
\$\begingroup\$

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?

mdfst13
22.4k6 gold badges34 silver badges70 bronze badges
asked Aug 30, 2021 at 15:40
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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');
answered Aug 31, 2021 at 22:34
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.