MCPcopy Create free account
hub / github.com/zenstackhq/zenstack / buildSort

Method buildSort

packages/server/src/api/rest/index.ts:2382–2457  ·  view source on GitHub ↗
(type: string, query: Record<string, string | string[]> | undefined)

Source from the content-addressed store, hash-verified

2380 }
2381
2382 private buildSort(type: string, query: Record<string, string | string[]> | undefined) {
2383 if (!query?.['sort']) {
2384 return { sort: undefined, error: undefined };
2385 }
2386
2387 const typeInfo = this.getModelInfo(type);
2388 if (!typeInfo) {
2389 return { sort: undefined, error: this.makeUnsupportedModelError(type) };
2390 }
2391
2392 const result: any[] = [];
2393
2394 for (const sortSpec of enumerate(query['sort'])) {
2395 const sortFields = sortSpec.split(',').filter((i) => i);
2396
2397 for (const sortField of sortFields) {
2398 const dir = sortField.startsWith('-') ? 'desc' : 'asc';
2399 const cleanedSortField = sortField.startsWith('-') ? sortField.substring(1) : sortField;
2400 const parts = cleanedSortField.split('.').filter((i) => i);
2401
2402 const sortItem: any = {};
2403 let curr = sortItem;
2404 let currType = typeInfo;
2405
2406 for (let i = 0; i < parts.length; i++) {
2407 const part = parts[i]!;
2408
2409 const fieldInfo = currType.fields[part];
2410 if (!fieldInfo || fieldInfo.array) {
2411 return {
2412 sort: undefined,
2413 error: this.makeError('invalidSort', 'sorting by array field is not supported'),
2414 };
2415 }
2416
2417 if (i === parts.length - 1) {
2418 if (fieldInfo.relation) {
2419 // relation field: sort by id
2420 const relationType = this.getModelInfo(fieldInfo.type);
2421 if (!relationType) {
2422 return { sort: undefined, error: this.makeUnsupportedModelError(fieldInfo.type) };
2423 }
2424 curr[fieldInfo.name] = relationType.idFields.reduce((acc: any, idField: FieldDef) => {
2425 acc[idField.name] = dir;
2426 return acc;
2427 }, {});
2428 } else {
2429 // regular field
2430 curr[fieldInfo.name] = dir;
2431 }
2432 } else {
2433 if (!fieldInfo.relation) {
2434 // must be a relation field
2435 return {
2436 sort: undefined,
2437 error: this.makeError(
2438 'invalidSort',
2439 'intermediate sort segments must be relationships',

Callers 2

processCollectionReadMethod · 0.95
injectRelationQueryMethod · 0.95

Calls 5

getModelInfoMethod · 0.95
makeErrorMethod · 0.95
enumerateFunction · 0.90
pushMethod · 0.80

Tested by

no test coverage detected