11/* eslint-disable no-use-before-define */
22
33import type { Model , Document } from 'mongoose' ;
4- import type {
4+ import {
55 ObjectTypeComposerArgumentConfigMapDefinition ,
66 ObjectTypeComposer ,
77 SchemaComposer ,
88 EnumTypeComposer ,
9+ isObject ,
910} from 'graphql-compose' ;
1011import { getIndexesFromModel , extendByReversedIndexes } from '../../utils/getIndexesFromModel' ;
1112import type { ExtendedResolveParams } from '../index' ;
1213
1314export type SortHelperArgsOpts = {
1415 sortTypeName ?: string ;
16+ /**
17+ * Allow sort by several fields.
18+ * This makes arg as array of sort values.
19+ */
20+ multi ?: boolean ;
1521} ;
1622
1723export function sortHelperArgs < TDoc extends Document = any > (
@@ -35,14 +41,34 @@ export function sortHelperArgs<TDoc extends Document = any>(
3541
3642 return {
3743 sort : {
38- type : gqSortType ,
44+ type : opts ?. multi ? gqSortType . NonNull . List : gqSortType ,
3945 } ,
4046 } ;
4147}
4248
4349export function sortHelper ( resolveParams : ExtendedResolveParams ) : void {
44- const sort = resolveParams && resolveParams . args && resolveParams . args . sort ;
45- if ( sort && typeof sort === 'object' && Object . keys ( sort ) . length > 0 ) {
50+ const _sort = resolveParams ?. args ?. sort ;
51+ if ( ! _sort ) return ;
52+
53+ let sort : Record < string , any > ;
54+ if ( Array . isArray ( _sort ) ) {
55+ sort = { } ;
56+ // combine array in one object,
57+ // keep only first key occurrence (rest skip)
58+ _sort . forEach ( ( o ) => {
59+ if ( isObject ( o ) ) {
60+ Object . keys ( o ) . forEach ( ( key ) => {
61+ if ( ! sort . hasOwnProperty ( key ) ) {
62+ sort [ key ] = ( o as any ) [ key ] ;
63+ }
64+ } ) ;
65+ }
66+ } ) ;
67+ } else {
68+ sort = _sort ;
69+ }
70+
71+ if ( typeof sort === 'object' && Object . keys ( sort ) . length > 0 ) {
4672 resolveParams . query = resolveParams . query . sort ( sort ) ;
4773 }
4874}
0 commit comments