All files / utils/api defineQueryBigQuery.ts

80.16% Statements 190/237
70.21% Branches 33/47
100% Functions 5/5
80.16% Lines 190/237

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 2381x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x     18x 18x 18x 1x 1x 18x 18x     18x 18x     1x 1x 22x     22x 22x 2x 2x 2x 20x 22x 2x 2x 2x 18x 22x 18x 18x     18x 18x       1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x 16x 5x 5x 5x 5x 5x 16x 16x 11x 11x 2x 2x 2x     2x 2x 11x 9x 9x 9x     9x 9x 11x 16x 16x 16x 16x 16x 16x 16x                                             16x 16x 16x 16x 16x 16x 16x 16x 1x 16x 1x 1x 1x 1x 16x 15x 15x 16x 16x 16x 16x           16x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 5x 3x 3x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 3x 4x 4x 5x     5x  
import { CustomError } from '../error'
 
interface IBuildRequestHandler {
  primaryEntity: boolean
  requestBody: any
  entity: string
  dataset: string
  table: string
  entityDef: Record<string, any>
  foreignKey?: string
  primaryKey?: string
}
 
const mapOperatorToSql = (operator: string) => {
  const operatorMap = {
    equals: '=',
    notEquals: '!=',
    lessThan: '<',
    lessOrEquals: '<=',
    greaterThan: '>',
    greaterOrEquals: '>=',
    includes: 'LIKE',
    notIncludes: 'NOT LIKE',
    in: 'IN',
    notIn: 'NOT IN',
    // Add more operators as needed
  }
 
  if (operatorMap[operator as keyof typeof operatorMap] === undefined) {
    throw new Error(`Operator ${operator} is not supported`)
  }
 
  return operatorMap[operator as keyof typeof operatorMap]
}
 
const formatValueForSql = (value: any) => {
  if (typeof value === 'string') {
    if (value.includes('(') && value.includes(')')) {
      return value
    }
    return `'${value}'`
  }
  return value
}
 
const parseFilterToSql = (filter: any) => {
  if (!filter) {
    return ''
  }
 
  if (filter.or) {
    const orConditions = filter.or.map((f) => parseFilterToSql(f))
    return `(${orConditions.join(' OR ')})`
  }
 
  if (filter.and) {
    const andConditions = filter.and.map((f) => parseFilterToSql(f))
    return `(${andConditions.join(' AND ')})`
  }
 
  if (filter.operator && filter.field && filter.value) {
    const { operator, field, value } = filter
    if (operator === 'in' || operator === 'notIn') {
      return `${formatValueForSql(value)} ${mapOperatorToSql(operator)} UNNEST(${field})`
    }
    return `${field} ${mapOperatorToSql(operator)} ${formatValueForSql(value)}`
  }

  return ''
}
 
const defineQueryHandler = (props: IBuildRequestHandler) => {
  try {
    const {
      primaryEntity,
      requestBody,
      entity,
      dataset,
      table,
      primaryKey,
      foreignKey,
      entityDef,
    } = props
 
    let query = '',
      metaQuery = ''
 
    // Always retrieve all fields.  We will remove unwanted
    // fields after building relationships.
    query = `SELECT * FROM ${dataset}.${table}`
    metaQuery = `SELECT COUNT(*) AS count FROM ${dataset}.${table}`
 
    /**
     * Filter handler
     */
    if (
      (requestBody.filter && requestBody.filter[entity]) ||
      primaryKey ||
      foreignKey
    ) {
      if (requestBody.filter && requestBody.filter[entity]) {
        query += ' WHERE '
        query += parseFilterToSql(requestBody.filter[entity])
        metaQuery += ' WHERE '
        metaQuery += parseFilterToSql(requestBody.filter[entity])
      }
 
      if (primaryKey || foreignKey) {
        const relationshipType = entityDef.type
        if (relationshipType === 'has-many' && foreignKey) {
          if (query.indexOf('WHERE') === -1) {
            query += ' WHERE '
          } else {
            query += ' AND '
          }
          query += `${foreignKey} = {{foreignIdentifier}}`
        }
        if (relationshipType === 'has-one' && primaryKey) {
          if (query.indexOf('WHERE') === -1) {
            query += ' WHERE '
          } else {
            query += ' AND '
          }
          query += `${primaryKey} = {{foreignIdentifier}}`
        }
      }
    }
    /* END Filter handler */
 
    /**
     * Sort handler
     */
    if (requestBody.sort && requestBody.sort[entity]) {
      const sorts = requestBody.sort[entity]
      query += ' ORDER BY'

      for (let i = 0; i < sorts.length; i++) {
        const sort = sorts[i]
        if (sort[0] === '-') {
          query += ` ${sort.slice(1).trim()} DESC`
          if (i < sorts.length - 1) {
            query += ','
          } else {
            query += ' '
          }
        } else {
          query += ` ${sort.trim()}`
          if (i < sorts.length - 1) {
            query += ','
          } else {
            query += ' '
          }
        }
      }
    }
    /* END Sort handler */
 
    /**
     * Pagination handler
     */
    if (
      primaryEntity &&
      requestBody.pagination &&
      requestBody.pagination.size
    ) {
      const size = requestBody.pagination.size
      const page = requestBody.pagination.page || 1
      const offset = (page - 1) * size
      query += ` LIMIT ${size} OFFSET ${offset}`
    } else {
      query += ' LIMIT 1000'
    }
    /* END Pagination handler */
 
    return { query, metaQuery }
  } catch (error: any) {
    throw new CustomError(
      `[buildBigQueryDataStoreRequest] ${error.message}`,
      400
    )
  }
}
 
export default (req: any) => {
  try {
    const { body, entityDef, path } = req
    const pathParts = path.split('/')
    const primaryEntity = pathParts[pathParts.length - 1]
    const entity = req.params.children ?? req.params.entity
    const { repo, dataset, table } = entityDef
    const requestBody = body
 
    const response = {
      primary: '',
      secondary: {},
      metaQuery: '',
    }
    let result = defineQueryHandler({
      primaryEntity,
      requestBody,
      entity,
      dataset,
      table,
      entityDef,
    })
    response.primary = result.query
    response.metaQuery = result.metaQuery
 
    if (req.settings.requestType === 'json') return response
 
    // Includes handler
    if (requestBody.includes) {
      const includes = requestBody.includes
      for (let childEntity of includes) {
        response.secondary[childEntity] = {}
        childEntity = childEntity.trim()
        const childEntityDef = entityDef.relationships[childEntity]
        const { dataset, table, foreignKey, primaryKey } = childEntityDef
        result = defineQueryHandler({
          primaryEntity: false,
          requestBody,
          entity: childEntity,
          dataset,
          table,
          primaryKey,
          foreignKey,
          entityDef: childEntityDef,
        })
        response.secondary[childEntity] = result.query
      }
    }
 
    return response
  } catch (error: any) {
    throw new CustomError(`[defineQueryBigQuery] ${error.message}`, 400)
  }
}