首页 > 解决方案 > Improving loop that tries different URL variations until match

问题描述

I have build API that connects to ownCloud and gets directory content via WebDAV (using that library). Because I can't use regular expressions here and glob matching doesn't seem to work while using deep: true I have to check all variations of the folder name (because customers sometimes input all letters big or just last name big, but name normally) and that's how I ended with code below. It has a lot of repetition and I this there is a way to make it look better:

    // if not found then go level up
    let tryMainDir = false
    let validUrl = () => {
      let url = `${baseUrl}/${caseYearAndMonth}/${lastName} ${firstName} - ${formNumber}/Form`
      return tryMainDir ? url.replace(`/${caseYearAndMonth}`, '') : url
    }

    let isUrlValid = await client.exists(validUrl())
    const updateIsUrlValid = async () => {
      isUrlValid = await client.exists(validUrl())
      console.log(isUrlValid)
    }

   if(!isUrlValid){
      // some names are uppercase and ownCloud is case-sensitive
      do {
        if(!isUrlValid){
          lastName = lastName.toUpperCase()
          await updateIsUrlValid()
        }
        if(!isUrlValid){
          firstName = firstName.toUpperCase()
          await updateIsUrlValid()
        }
        if(!isUrlValid){
          firstName = firstName.toLowerCase()
          lastName = lastName.toLowerCase()
          await updateIsUrlValid()
        }
        if(!isUrlValid){
          firstName = firstName.charAt(0).toUpperCase() + firstName.slice(1)
          lastName = lastName.charAt(0).toUpperCase() + lastName.slice(1)
          await updateIsUrlValid()
        }
        if(!isUrlValid){
          firstName = firstName.charAt(0).toUpperCase() + firstName.slice(1)
          lastName = lastName.charAt(0).toUpperCase() + lastName.slice(1)
          await updateIsUrlValid()
        }
        if(!isUrlValid && tryMainDir){
          break;
        }
        if(!isUrlValid){
          tryMainDir = true
        }
      } while (!isUrlValid)
    }

The loop is supposed to do maximum two rounds. To look inside folder and then in parent directory.

标签: javascriptwebdavowncloud

解决方案


推荐阅读