1 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
2 import { Sequelize } from 'sequelize-typescript'
4 function getSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
6 let direction: 'ASC' | 'DESC'
8 if (value.substring(0, 1) === '-') {
10 field = value.substring(1)
17 if (field.toLowerCase() === 'match') field = Sequelize.col('similarity')
19 return [ [ field, direction ], lastSort ]
22 function getSortOnModel (model: any, value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
23 let [ firstSort ] = getSort(value)
25 if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
26 return [ firstSort, lastSort ]
29 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value') {
30 if (validator(value) === false) {
31 throw new Error(`"${value}" is not a valid ${fieldName}.`)
35 function buildTrigramSearchIndex (indexName: string, attribute: string) {
38 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
40 operator: 'gin_trgm_ops'
44 function createSimilarityAttribute (col: string, value: string) {
48 searchTrigramNormalizeCol(col),
50 searchTrigramNormalizeValue(value)
54 // ---------------------------------------------------------------------------
59 createSimilarityAttribute,
61 buildTrigramSearchIndex
64 // ---------------------------------------------------------------------------
66 function searchTrigramNormalizeValue (value: string) {
67 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
70 function searchTrigramNormalizeCol (col: string) {
71 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))