]>
Commit | Line | Data |
---|---|---|
3bb6c526 | 1 | // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ] |
57c36b27 C |
2 | import { Sequelize } from 'sequelize-typescript' |
3 | ||
06215f15 C |
4 | type SortType = { sortModel: any, sortValue: string } |
5 | ||
3bb6c526 | 6 | function getSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) { |
57c36b27 | 7 | let field: any |
69818c93 | 8 | let direction: 'ASC' | 'DESC' |
5c39adb7 | 9 | |
feb4bdfd C |
10 | if (value.substring(0, 1) === '-') { |
11 | direction = 'DESC' | |
12 | field = value.substring(1) | |
13 | } else { | |
14 | direction = 'ASC' | |
15 | field = value | |
16 | } | |
5c39adb7 | 17 | |
57c36b27 | 18 | // Alias |
d525fc39 | 19 | if (field.toLowerCase() === 'match') field = Sequelize.col('similarity') |
57c36b27 | 20 | |
3bb6c526 | 21 | return [ [ field, direction ], lastSort ] |
5c39adb7 C |
22 | } |
23 | ||
3bb6c526 C |
24 | function getSortOnModel (model: any, value: string, lastSort: string[] = [ 'id', 'ASC' ]) { |
25 | let [ firstSort ] = getSort(value) | |
792dbaf0 | 26 | |
3bb6c526 C |
27 | if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ] |
28 | return [ firstSort, lastSort ] | |
792dbaf0 GS |
29 | } |
30 | ||
3fd3ab2d C |
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 | ||
57c36b27 C |
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 | ||
5c39adb7 C |
56 | // --------------------------------------------------------------------------- |
57 | ||
65fcc311 | 58 | export { |
06215f15 | 59 | SortType, |
792dbaf0 | 60 | getSort, |
3fd3ab2d | 61 | getSortOnModel, |
57c36b27 C |
62 | createSimilarityAttribute, |
63 | throwIfNotValid, | |
dbfd3e9b | 64 | buildTrigramSearchIndex |
57c36b27 C |
65 | } |
66 | ||
67 | // --------------------------------------------------------------------------- | |
68 | ||
69 | function searchTrigramNormalizeValue (value: string) { | |
2cebd797 | 70 | return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value)) |
57c36b27 C |
71 | } |
72 | ||
73 | function searchTrigramNormalizeCol (col: string) { | |
74 | return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col))) | |
65fcc311 | 75 | } |