All files / v5/remove-overloads/transformers filter-aware-usage-transformer.js

0% Statements 0/61
0% Branches 0/36
0% Functions 0/7
0% Lines 0/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
// eslint-disable-next-line @typescript-eslint/no-var-requires
const createV5UtilsObject = require('../utils')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const UnknownUsageError = require('../utils/unknown-usage-error')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const createQueryClientTransformer = require('../../../utils/transformers/query-client-transformer')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const createQueryCacheTransformer = require('../../../utils/transformers/query-cache-transformer')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const createUseQueryLikeTransformer = require('../../../utils/transformers/use-query-like-transformer')
 
/**
 * @param {import('jscodeshift').api} jscodeshift
 * @param {Object} utils
 * @param {import('jscodeshift').Collection} root
 * @param {string} filePath
 * @param {{keyName: "mutationKey"|"queryKey", queryClientMethods: ReadonlyArray<string>, hooks: ReadonlyArray<string>}} config
 */
const transformFilterAwareUsages = ({
  jscodeshift,
  utils,
  root,
  filePath,
  config,
}) => {
  const v5Utils = createV5UtilsObject({ jscodeshift, utils })
 
  /**
   * @param {import('jscodeshift').CallExpression} node
   * @param {"mutationKey"|"queryKey"} keyName
   * @returns {boolean}
   */
  const canSkipReplacement = (node, keyName) => {
    const callArguments = node.arguments
 
    const hasKeyProperty = () =>
      callArguments[0].properties.some(
        (property) =>
          utils.isObjectProperty(property) && property.key.name !== keyName,
      )
 
    /**
     * This call has at least one argument. If it's an object expression and contains the "queryKey" or "mutationKey"
     * field, the transformation can be skipped, because it's already matching the expected signature.
     */
    return (
      callArguments.length > 0 &&
      utils.isObjectExpression(callArguments[0]) &&
      hasKeyProperty()
    )
  }
 
  /**
   * This function checks whether the given object property is a spread element or a property that's not named
   * "queryKey" or "mutationKey".
   *
   * @param {import('jscodeshift').ObjectProperty} property
   * @returns {boolean}
   */
  const predicate = (property) => {
    const isSpreadElement = utils.isSpreadElement(property)
    const isObjectProperty = utils.isObjectProperty(property)
 
    return (
      isSpreadElement ||
      (isObjectProperty && property.key.name !== config.keyName)
    )
  }
 
  const replacer = (path) => {
    const node = path.node
 
    const isFunctionDefinition = (functionArgument) => {
      if (utils.isFunctionDefinition(functionArgument)) {
        return true
      }
 
      if (utils.isIdentifier(functionArgument)) {
        const binding = v5Utils.getBindingFromScope(
          path,
          functionArgument.name,
          filePath,
        )
 
        const isVariableDeclarator = jscodeshift.match(binding, {
          type: jscodeshift.VariableDeclarator.name,
        })
 
        return isVariableDeclarator && utils.isFunctionDefinition(binding.init)
      }
    }
 
    try {
      // If the given method/function call matches certain criteria, the node doesn't need to be replaced, this step can be skipped.
      if (canSkipReplacement(node, config.keyName)) {
        return node
      }
 
      /**
       * Here we attempt to determine the first parameter of the function call. If it's an array expression or an
       * identifier that references an array expression then we create an object property from it.
       *
       * @type {import('jscodeshift').Property|undefined}
       */
      const keyProperty = v5Utils.transformArgumentToKey(
        path,
        node.arguments[0],
        config.keyName,
        filePath,
      )
 
      /**
       * The first parameter couldn't be transformed into an object property, so it's time to throw an exception,
       * it will notify the consumers that they need to rewrite this usage manually.
       */
      if (!keyProperty) {
        const secondArgument =
          node.arguments.length > 1 ? node.arguments[1] : null
 
        if (!secondArgument) {
          throw new UnknownUsageError(node, filePath)
        }
 
        if (utils.isFunctionDefinition(secondArgument)) {
          const originalArguments = node.arguments
          const firstArgument = jscodeshift.objectExpression([
            jscodeshift.property(
              'init',
              jscodeshift.identifier('queryKey'),
              originalArguments[0],
            ),
            jscodeshift.property(
              'init',
              jscodeshift.identifier('queryFn'),
              secondArgument,
            ),
          ])
 
          return jscodeshift.callExpression(node.original.callee, [
            firstArgument,
            ...originalArguments.slice(2),
          ])
        }
      }
 
      const functionArguments = [jscodeshift.objectExpression([keyProperty])]
      const secondParameter = node.arguments[1]
 
      if (secondParameter) {
        const createdObjectExpression = functionArguments[0]
 
        if (isFunctionDefinition(secondParameter)) {
          const objectExpression = jscodeshift.objectExpression([
            jscodeshift.property(
              'init',
              jscodeshift.identifier('queryKey'),
              node.arguments[0],
            ),
            jscodeshift.property(
              'init',
              jscodeshift.identifier('queryFn'),
              secondParameter,
            ),
          ])
 
          const thirdArgument = node.arguments[2]
 
          if (thirdArgument) {
            // If it's an object expression, we can copy the properties from it to the newly created object expression.
            if (utils.isObjectExpression(thirdArgument)) {
              v5Utils.copyPropertiesFromSource(
                thirdArgument,
                objectExpression,
                predicate,
              )
            } else {
              // Otherwise, we simply spread the third argument in the newly created object expression.
              objectExpression.properties.push(
                jscodeshift.spreadElement(thirdArgument),
              )
            }
          }
 
          return jscodeshift.callExpression(node.original.callee, [
            objectExpression,
          ])
        }
 
        /**
         * If it has a second argument, and it's an object expression, then we get the properties from it
         * (except the "queryKey" or "mutationKey" properties), because these arguments will also be moved to the
         * newly created object expression.
         */
        if (utils.isObjectExpression(secondParameter)) {
          v5Utils.copyPropertiesFromSource(
            secondParameter,
            createdObjectExpression,
            predicate,
          )
        } else {
          // Otherwise, we simply spread the second parameter in the newly created object expression.
          createdObjectExpression.properties.push(
            jscodeshift.spreadElement(secondParameter),
          )
        }
      }
 
      // The rest of the function arguments can be simply pushed to the function arguments object so all will be kept.
      functionArguments.push(...node.arguments.slice(2))
 
      return jscodeshift.callExpression(node.original.callee, functionArguments)
    } catch (error) {
      utils.warn(
        error.name === UnknownUsageError.name
          ? error.message
          : `An unknown error occurred while processing the "${filePath}" file. Please review this file, because the codemod couldn't be applied.`,
      )
 
      return node
    }
  }
 
  createQueryClientTransformer({ jscodeshift, utils, root }).execute(
    config.queryClientMethods,
    replacer,
  )
 
  createUseQueryLikeTransformer({ jscodeshift, utils, root }).execute(
    config.hooks,
    replacer,
  )
 
  createQueryCacheTransformer({ jscodeshift, utils, root }).execute(replacer)
}
 
module.exports = transformFilterAwareUsages