1

I've got 2 near-identical functions (NodeJS). One of them queries DB for shop information by its phone number, while the other one queries by its id. I'd like to know if there's a clean way to merge these 2 together.

async getShopInfo (phone) {
 try {
 let shopInfo = await shopConfigModel.getShopInfo(phone)
 if (shopInfo && shopInfo.length > 0) {
 return shopInfo
 }
 } catch (error) {
 logger.error('error on getShopInfo %s', error.message)
 }
 return null
}
async getShopInfoById (shopId) {
 try {
 let shopInfo = await shopConfigModel.getShopInfoById(shopId)
 if (shopInfo && shopInfo.length > 0) {
 return shopInfo
 }
 } catch (error) {
 logger.error('error on getShopInfo %s', error.message)
 }
 return null
}
asked Jan 6, 2020 at 2:27
2

2 Answers 2

2

Assuming you want to keep shopConfigModel private, you could factor out your validation logic into a function and have it handle the common code.

async function validate(pendingShopInfo) {
 try {
 const shopInfo = await pendingShopInfo
 return shopInfo.length ? shopInfo : null
 } catch (error) {
 logger.error('error on getShopInfo %s', error.message)
 return null
 }
}
export const getShopInfo = phone => validate(shopConfigModel.getShopInfo(phone))
export const getShopInfoById = id => validate(shopConfigModel.getShopInfoById(id))

(The above code snippet also accounts for the async / promise stuff.)

This is very similar to a previous answer with the main difference being the public interface doesn't require anyone to know about shopConfigModel.

answered Feb 16, 2020 at 6:10
1

Adding to Victor's comment, simplifying and exploiting ES6 for varargs

function getInfo(howFn, ...info) {
 try {
 return howFn(...info);
 } catch (error) {
 logger.error(this part needs a little work);
 }
}
// Calls
let shopInfo = getInfo(shopConfigModel.getShopInfo, phone);
let shopInfo = getInfo(shopConfigModel.getShopInfoById, shopId);

Followup: In this extremely simplified example, not sure if this refactoring makes much sense. But, if the requirements were more complex, say it had to check if the user had proper permissions, then open up a database or URL, and only then call howFn(), or if the error handling was also more complex, this this makes a lot more sense.

answered Jan 6, 2020 at 5:02

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.