aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/shared/sequelize-helpers.ts
blob: 7af8471dc51f17aa31dc41f60f5ea231d159ec77 (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
import { Sequelize } from 'sequelize'

function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
  if (!model.createdAt || !model.updatedAt) {
    throw new Error('Miss createdAt & updatedAt attributes to model')
  }

  const now = Date.now()
  const createdAtTime = model.createdAt.getTime()
  const updatedAtTime = model.updatedAt.getTime()

  return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
}

function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
  if (nullable && (value === null || value === undefined)) return

  if (validator(value) === false) {
    throw new Error(`"${value}" is not a valid ${fieldName}.`)
  }
}

function buildTrigramSearchIndex (indexName: string, attribute: string) {
  return {
    name: indexName,
    // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
    fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
    using: 'gin',
    operator: 'gin_trgm_ops'
  }
}

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

export {
  throwIfNotValid,
  buildTrigramSearchIndex,
  isOutdated
}