aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/shared/query.ts
blob: 934acc21f7c364aca4e27fcfebb4498f9019d5d0 (plain) (blame)
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
import { BindOrReplacements, Op, QueryTypes, Sequelize } from 'sequelize'
import validator from 'validator'
import { forceNumber } from '@shared/core-utils'

function doesExist (sequelize: Sequelize, query: string, bind?: BindOrReplacements) {
  const options = {
    type: QueryTypes.SELECT as QueryTypes.SELECT,
    bind,
    raw: true
  }

  return sequelize.query(query, options)
            .then(results => results.length === 1)
}

function createSimilarityAttribute (col: string, value: string) {
  return Sequelize.fn(
    'similarity',

    searchTrigramNormalizeCol(col),

    searchTrigramNormalizeValue(value)
  )
}

function buildWhereIdOrUUID (id: number | string) {
  return validator.isInt('' + id) ? { id } : { uuid: id }
}

function parseAggregateResult (result: any) {
  if (!result) return 0

  const total = forceNumber(result)
  if (isNaN(total)) return 0

  return total
}

function parseRowCountResult (result: any) {
  if (result.length !== 0) return result[0].total

  return 0
}

function createSafeIn (sequelize: Sequelize, toEscape: (string | number)[], additionalUnescaped: string[] = []) {
  return toEscape.map(t => {
    return t === null
      ? null
      : sequelize.escape('' + t)
  }).concat(additionalUnescaped).join(', ')
}

function searchAttribute (sourceField?: string, targetField?: string) {
  if (!sourceField) return {}

  return {
    [targetField]: {
      // FIXME: ts error
      [Op.iLike as any]: `%${sourceField}%`
    }
  }
}

export {
  doesExist,
  createSimilarityAttribute,
  buildWhereIdOrUUID,
  parseAggregateResult,
  parseRowCountResult,
  createSafeIn,
  searchAttribute
}

// ---------------------------------------------------------------------------

function searchTrigramNormalizeValue (value: string) {
  return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
}

function searchTrigramNormalizeCol (col: string) {
  return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
}