1 import { Sequelize } from 'sequelize-typescript'
3 type SortType = { sortModel: any, sortValue: string }
5 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
6 function getSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
7 const { direction, field } = buildDirectionAndField(value)
9 return [ [ field, direction ], lastSort ]
12 function getVideoSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
13 let { direction, field } = buildDirectionAndField(value)
16 if (field.toLowerCase() === 'match') field = Sequelize.col('similarity')
18 // Sort by aggregation
19 if (field.toLowerCase() === 'trending') {
21 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
23 [ Sequelize.col('VideoModel.views'), direction ],
29 return [ [ field, direction ], lastSort ]
32 function getSortOnModel (model: any, value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
33 let [ firstSort ] = getSort(value)
35 if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
36 return [ firstSort, lastSort ]
39 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value') {
40 if (validator(value) === false) {
41 throw new Error(`"${value}" is not a valid ${fieldName}.`)
45 function buildTrigramSearchIndex (indexName: string, attribute: string) {
48 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
50 operator: 'gin_trgm_ops'
54 function createSimilarityAttribute (col: string, value: string) {
58 searchTrigramNormalizeCol(col),
60 searchTrigramNormalizeValue(value)
64 // ---------------------------------------------------------------------------
71 createSimilarityAttribute,
73 buildTrigramSearchIndex
76 // ---------------------------------------------------------------------------
78 function searchTrigramNormalizeValue (value: string) {
79 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
82 function searchTrigramNormalizeCol (col: string) {
83 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
86 function buildDirectionAndField (value: string) {
88 let direction: 'ASC' | 'DESC'
90 if (value.substring(0, 1) === '-') {
92 field = value.substring(1)
98 return { direction, field }