-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
aggregate.ts
38 lines (35 loc) · 1.25 KB
/
aggregate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { type AllCollections } from '../../../index.js';
import { throwIfEmpty } from '../../utils/index.js';
import type { AggregationOptions, AggregationOutput } from '../../../types/aggregate.js';
import type { RestCommand } from '../../types.js';
import { isSystemCollection } from '@directus/system-data';
/**
* Aggregate allow you to perform calculations on a set of values, returning a single result.
* @param collection The collection to aggregate
* @param options The aggregation options
* @returns Aggregated data
* @throws Will throw if collection is empty
*/
export const aggregate =
<
Schema extends object,
Collection extends AllCollections<Schema>,
Options extends AggregationOptions<Schema, Collection>,
>(
collection: Collection,
options: Options,
): RestCommand<AggregationOutput<Schema, Collection, Options>, Schema> =>
() => {
const collectionName = String(collection);
throwIfEmpty(collectionName, 'Collection cannot be empty');
const path = isSystemCollection(collectionName) ? `/${collectionName.substring(9)}` : `/items/${collectionName}`;
return {
path,
method: 'GET',
params: {
...(options.query ?? {}),
...(options.groupBy ? { groupBy: options.groupBy } : {}),
aggregate: options.aggregate,
},
};
};