+ 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 getSortOnModel (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
+ const [ firstSort ] = getSort(value)
+
+ if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
+ 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}.`)