]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/utils.ts
add postgresql96-contrib to the FreeBSD dependencies (#958)
[github/Chocobozzz/PeerTube.git] / server / models / utils.ts
1 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
2 import { Sequelize } from 'sequelize-typescript'
3
4 type SortType = { sortModel: any, sortValue: string }
5
6 function getSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
7 let field: any
8 let direction: 'ASC' | 'DESC'
9
10 if (value.substring(0, 1) === '-') {
11 direction = 'DESC'
12 field = value.substring(1)
13 } else {
14 direction = 'ASC'
15 field = value
16 }
17
18 // Alias
19 if (field.toLowerCase() === 'match') field = Sequelize.col('similarity')
20
21 return [ [ field, direction ], lastSort ]
22 }
23
24 function getSortOnModel (model: any, value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
25 let [ firstSort ] = getSort(value)
26
27 if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
28 return [ firstSort, lastSort ]
29 }
30
31 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value') {
32 if (validator(value) === false) {
33 throw new Error(`"${value}" is not a valid ${fieldName}.`)
34 }
35 }
36
37 function buildTrigramSearchIndex (indexName: string, attribute: string) {
38 return {
39 name: indexName,
40 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
41 using: 'gin',
42 operator: 'gin_trgm_ops'
43 }
44 }
45
46 function createSimilarityAttribute (col: string, value: string) {
47 return Sequelize.fn(
48 'similarity',
49
50 searchTrigramNormalizeCol(col),
51
52 searchTrigramNormalizeValue(value)
53 )
54 }
55
56 // ---------------------------------------------------------------------------
57
58 export {
59 SortType,
60 getSort,
61 getSortOnModel,
62 createSimilarityAttribute,
63 throwIfNotValid,
64 buildTrigramSearchIndex
65 }
66
67 // ---------------------------------------------------------------------------
68
69 function searchTrigramNormalizeValue (value: string) {
70 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
71 }
72
73 function searchTrigramNormalizeCol (col: string) {
74 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
75 }