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
}
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.

| improve this answer | |
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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.