]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/utils.ts
Fix last commit
[github/Chocobozzz/PeerTube.git] / server / models / utils.ts
CommitLineData
3bb6c526 1// Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
57c36b27
C
2import { Sequelize } from 'sequelize-typescript'
3
3bb6c526 4function getSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
57c36b27 5 let field: any
69818c93 6 let direction: 'ASC' | 'DESC'
5c39adb7 7
feb4bdfd
C
8 if (value.substring(0, 1) === '-') {
9 direction = 'DESC'
10 field = value.substring(1)
11 } else {
12 direction = 'ASC'
13 field = value
14 }
5c39adb7 15
57c36b27 16 // Alias
d525fc39 17 if (field.toLowerCase() === 'match') field = Sequelize.col('similarity')
57c36b27 18
3bb6c526 19 return [ [ field, direction ], lastSort ]
5c39adb7
C
20}
21
3bb6c526
C
22function getSortOnModel (model: any, value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
23 let [ firstSort ] = getSort(value)
792dbaf0 24
3bb6c526
C
25 if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
26 return [ firstSort, lastSort ]
792dbaf0
GS
27}
28
3fd3ab2d
C
29function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value') {
30 if (validator(value) === false) {
31 throw new Error(`"${value}" is not a valid ${fieldName}.`)
32 }
33}
34
57c36b27
C
35function buildTrigramSearchIndex (indexName: string, attribute: string) {
36 return {
37 name: indexName,
38 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
39 using: 'gin',
40 operator: 'gin_trgm_ops'
41 }
42}
43
44function createSimilarityAttribute (col: string, value: string) {
45 return Sequelize.fn(
46 'similarity',
47
48 searchTrigramNormalizeCol(col),
49
50 searchTrigramNormalizeValue(value)
51 )
52}
53
54function createSearchTrigramQuery (col: string, value: string) {
55 return {
56 [ Sequelize.Op.or ]: [
57 // FIXME: use word_similarity instead of just similarity?
58 Sequelize.where(searchTrigramNormalizeCol(col), ' % ', searchTrigramNormalizeValue(value)),
59
60 Sequelize.where(searchTrigramNormalizeCol(col), ' LIKE ', searchTrigramNormalizeValue(`%${value}%`))
61 ]
62 }
63}
64
5c39adb7
C
65// ---------------------------------------------------------------------------
66
65fcc311 67export {
792dbaf0 68 getSort,
3fd3ab2d 69 getSortOnModel,
57c36b27
C
70 createSimilarityAttribute,
71 throwIfNotValid,
72 buildTrigramSearchIndex,
73 createSearchTrigramQuery
74}
75
76// ---------------------------------------------------------------------------
77
78function searchTrigramNormalizeValue (value: string) {
2cebd797 79 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
57c36b27
C
80}
81
82function searchTrigramNormalizeCol (col: string) {
83 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
65fcc311 84}