All files / v4/utils/replacers key-replacer.js

0% Statements 0/60
0% Branches 0/35
0% Functions 0/15
0% Lines 0/60

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                                                                                                                                                                                                                                                                                                                                         
class UnprocessableKeyError extends Error {
  constructor(message) {
    super(message)
    this.name = 'UnprocessableKeyError'
  }
}
 
module.exports = ({ jscodeshift, root, filePath, keyName = 'queryKey' }) => {
  const isArrayExpression = (node) =>
    jscodeshift.match(node, { type: jscodeshift.ArrayExpression.name })
 
  const isStringLiteral = (node) =>
    jscodeshift.match(node, { type: jscodeshift.StringLiteral.name }) ||
    jscodeshift.match(node, { type: jscodeshift.Literal.name })
 
  const isTemplateLiteral = (node) =>
    jscodeshift.match(node, { type: jscodeshift.TemplateLiteral.name })
 
  const findVariableDeclaration = (node) => {
    const declarations = root
      .find(jscodeshift.VariableDeclarator, {
        id: {
          type: jscodeshift.Identifier.name,
          name: node.name,
        },
      })
      .paths()
 
    return declarations.length > 0 ? declarations[0] : null
  }
 
  const createKeyValue = (node) => {
    // When the node is a string literal we convert it into an array of strings.
    if (isStringLiteral(node)) {
      return jscodeshift.arrayExpression([
        jscodeshift.stringLiteral(node.value),
      ])
    }
 
    // When the node is a template literal we convert it into an array of template literals.
    if (isTemplateLiteral(node)) {
      return jscodeshift.arrayExpression([
        jscodeshift.templateLiteral(node.quasis, node.expressions),
      ])
    }
 
    if (jscodeshift.match(node, { type: jscodeshift.Identifier.name })) {
      // When the node is an identifier at first, we try to find its declaration, because we will try
      // to guess its type.
      const variableDeclaration = findVariableDeclaration(node)
 
      if (!variableDeclaration) {
        throw new UnprocessableKeyError(
          `In file ${filePath} at line ${node.loc.start.line} the type of identifier \`${node.name}\` couldn't be recognized, so the codemod couldn't be applied. Please migrate manually.`,
        )
      }
 
      const initializer = variableDeclaration.value.init
 
      // When it's a string, we just wrap it into an array expression.
      if (isStringLiteral(initializer) || isTemplateLiteral(initializer)) {
        return jscodeshift.arrayExpression([node])
      }
    }
 
    throw new UnprocessableKeyError(
      `In file ${filePath} at line ${node.loc.start.line} the type of the \`${keyName}\` couldn't be recognized, so the codemod couldn't be applied. Please migrate manually.`,
    )
  }
 
  const createKeyProperty = (node) =>
    jscodeshift.property(
      'init',
      jscodeshift.identifier(keyName),
      createKeyValue(node),
    )
 
  const getPropertyFromObjectExpression = (objectExpression, propertyName) =>
    objectExpression.properties.find(
      (property) => property.key.name === propertyName,
    ) ?? null
 
  const buildWithTypeArguments = (node, builder) => {
    const newNode = builder(node)
 
    if (node.typeParameters) {
      newNode.typeArguments = node.typeParameters
    }
 
    return newNode
  }
 
  return ({ node }) => {
    // When the node doesn't have the 'original' property, that means the codemod has been already applied,
    // so we don't need to do any changes.
    if (!node.original) {
      return node
    }
 
    const methodArguments = node.arguments
 
    // The method call doesn't have any arguments, we have nothing to do in this case.
    if (methodArguments.length === 0) {
      return node
    }
 
    try {
      const [firstArgument, ...restOfTheArguments] = methodArguments
 
      if (
        jscodeshift.match(firstArgument, {
          type: jscodeshift.ObjectExpression.name,
        })
      ) {
        const originalKey = getPropertyFromObjectExpression(
          firstArgument,
          keyName,
        )
 
        if (!originalKey) {
          throw new UnprocessableKeyError(
            `In file ${filePath} at line ${node.loc.start.line} the \`${keyName}\` couldn't be found. Did you forget to add it?`,
          )
        }
 
        const restOfTheProperties = firstArgument.properties.filter(
          (item) => item.key.name !== keyName,
        )
 
        return buildWithTypeArguments(node, (originalNode) =>
          jscodeshift.callExpression(originalNode.original.callee, [
            jscodeshift.objectExpression([
              createKeyProperty(originalKey.value),
              ...restOfTheProperties,
            ]),
            ...restOfTheArguments,
          ]),
        )
      }
 
      // When the node is an array expression we just simply return it because we want query keys to be arrays.
      if (isArrayExpression(firstArgument)) {
        return node
      }
 
      return buildWithTypeArguments(node, (originalNode) =>
        jscodeshift.callExpression(originalNode.original.callee, [
          createKeyValue(firstArgument),
          ...restOfTheArguments,
        ]),
      )
    } catch (error) {
      if (error.name === 'UnprocessableKeyError') {
        if (process.env.NODE_ENV !== 'test') {
          console.warn(error.message)
        }
 
        return node
      }
 
      throw error
    }
  }
}