X-Git-Url: https://git.librecmc.org/?a=blobdiff_plain;f=server%2Fmodels%2Futils.ts;h=59ce83c16e09a79b3fbeac8a97a2b016b0e6e7a5;hb=7b87d2d5141d0eb48db2a3fd162208d6a79b2035;hp=601811913d5d24dde4aedcd7486882638ab3ef86;hpb=65fcc3119c334b75dd13bcfdebf186afdc580a8f;p=oweals%2Fpeertube.git diff --git a/server/models/utils.ts b/server/models/utils.ts index 601811913..59ce83c16 100644 --- a/server/models/utils.ts +++ b/server/models/utils.ts @@ -1,7 +1,7 @@ -// Translate for example "-name" to [ 'name', 'DESC' ] -function getSort (value) { - let field - let direction +// Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ] +function getSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) { + let field: string + let direction: 'ASC' | 'DESC' if (value.substring(0, 1) === '-') { direction = 'DESC' @@ -11,11 +11,26 @@ function getSort (value) { field = value } - return [ field, direction ] + return [ [ field, direction ], lastSort ] +} + +function getSortOnModel (model: any, value: string, lastSort: string[] = [ 'id', 'ASC' ]) { + let [ firstSort ] = getSort(value) + + if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ] + return [ firstSort, lastSort ] +} + +function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value') { + if (validator(value) === false) { + throw new Error(`"${value}" is not a valid ${fieldName}.`) + } } // --------------------------------------------------------------------------- export { - getSort + getSort, + getSortOnModel, + throwIfNotValid }