+ finalField = field
+ }
+
+ return [ [ finalField, direction ], lastSort ]
+}
+
+function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
+ const { direction, field } = buildDirectionAndField(value)
+
+ if (field.toLowerCase() === 'trending') { // Sort by aggregation
+ return [
+ [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
+
+ [ Sequelize.col('VideoModel.views'), direction ],
+
+ lastSort
+ ]
+ }
+
+ let finalField: string | Col
+
+ // Alias
+ if (field.toLowerCase() === 'match') { // Search
+ finalField = Sequelize.col('similarity')
+ } else {
+ finalField = field
+ }
+
+ const firstSort = typeof finalField === 'string'
+ ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
+ : [ finalField, direction ]
+
+ return [ firstSort, lastSort ]
+}
+
+function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
+ const [ firstSort ] = getSort(value)
+
+ if (model) return [ [ literal(`"${model}.${firstSort[ 0 ]}" ${firstSort[ 1 ]}`) ], lastSort ] as any[] // FIXME: typings
+ return [ firstSort, lastSort ]
+}
+
+function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
+ const now = Date.now()
+ const createdAtTime = model.createdAt.getTime()
+ const updatedAtTime = model.updatedAt.getTime()
+
+ return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
+}
+
+function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
+ if (nullable && (value === null || value === undefined)) return
+
+ if (validator(value) === false) {
+ throw new Error(`"${value}" is not a valid ${fieldName}.`)
+ }
+}
+
+function buildTrigramSearchIndex (indexName: string, attribute: string) {
+ return {
+ name: indexName,
+ fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
+ using: 'gin',
+ operator: 'gin_trgm_ops'