diff --git a/src/parameter/sort/parse.ts b/src/parameter/sort/parse.ts index 82e98887..e948de94 100644 --- a/src/parameter/sort/parse.ts +++ b/src/parameter/sort/parse.ts @@ -8,7 +8,7 @@ import { ObjectLiteral } from '../../type'; import { applyMapping, - buildFieldWithPath, flattenNestedObject, + buildFieldWithPath, buildKeyPath, flattenNestedObject, getFieldDetails, hasOwnProperty, isFieldNonRelational, isFieldPathAllowedByRelations, @@ -44,9 +44,16 @@ function buildDefaultSortParseOutput( for (let i = 0; i < keys.length; i++) { const fieldDetails = getFieldDetails(keys[i]); + let path : string | undefined; + if (fieldDetails.path) { + path = fieldDetails.path; + } else if (options.defaultPath) { + path = options.defaultPath; + } + output.push({ key: fieldDetails.name, - ...(fieldDetails.path ? { alias: fieldDetails.path } : {}), + ...(path ? { path } : {}), value: flatten[keys[i]], }); } @@ -176,10 +183,17 @@ export function parseQuerySort( const keyPaths = flattenParseOptionsAllowed(options.allowed[i]); for (let j = 0; j < keyPaths.length; j++) { - const keyWithAlias : string = keyPaths[j]; - const key : string = keyWithAlias.includes('.') ? - keyWithAlias.split('.').pop() : - keyWithAlias; + let keyWithAlias : string = keyPaths[j]; + let key : string; + + const parts = keyWithAlias.split('.'); + if (parts.length > 0) { + key = parts.pop(); + } else { + key = keyWithAlias; + + keyWithAlias = buildKeyPath(key, options.defaultPath); + } if ( hasOwnProperty(items, key) || diff --git a/src/utils/index.ts b/src/utils/index.ts index 29557d19..95096afd 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -8,6 +8,7 @@ export * from './array'; export * from './mapping'; export * from './field'; +export * from './key'; export * from './relation'; export * from './object'; export * from './simple'; diff --git a/src/utils/key.ts b/src/utils/key.ts new file mode 100644 index 00000000..71092b11 --- /dev/null +++ b/src/utils/key.ts @@ -0,0 +1,7 @@ +export function buildKeyWithPrefix(name: string, prefix?: string) { + if (prefix) { + return `${prefix}.${name}`; + } + + return name; +} diff --git a/test/unit/fields.spec.ts b/test/unit/fields.spec.ts index f88047eb..063a342a 100644 --- a/test/unit/fields.spec.ts +++ b/test/unit/fields.spec.ts @@ -34,8 +34,23 @@ describe('src/fields/index.ts', () => { defaultPath: 'user' }; - let data = parseQueryFields('+email', options); + let data = parseQueryFields([], options); + expect(data).toEqual([ + { + key: 'id', + path: 'user' + }, + { + key: 'name', + path: 'user' + }, + { + key: 'email', + path: 'user' + } + ] as FieldsParseOutput); + data = parseQueryFields('+email', options); expect(data).toEqual([ { key: 'email',