Skip to content
中文

Aggregation: query aggregation and stable merging ​

Read App data in order and keep how duplicate items are merged in the same configuration.

collect(inputs, context) calls execute synchronously and returns {total,items}. Without a key every result is kept; with a key, merging is stable by first insertion position and later items override earlier ones by default. merge(item,previous,input,context) can decide which result to keep. execute, key, and merge must all be synchronous.

mergeByKey is an independent merge function for the same purpose. It does not query a database, call a model, or manage transactions or permissions; those remain the responsibility of the real read port.

Progressive examples for the same business case ​

Aggregate two reads in order ​

Beginner · Node.js

ts
import { Aggregation } from '@jangts/agent-core/kits/aggregation';
const pages = new Map([[1, [{ id: 'a', title: '第一页' }]], [2, [{ id: 'a', title: '重复项' }, { id: 'b', title: '第二页' }]]]);
const query = Aggregation.defineQueryAggregation({ execute: (page: number) => pages.get(page) ?? [] });
console.log(query.collect([1, 2], undefined));
js
import { Aggregation } from '@jangts/agent-core/kits/aggregation';
const pages = new Map([[1, [{ id: 'a', title: '第一页' }]], [2, [{ id: 'a', title: '重复项' }, { id: 'b', title: '第二页' }]]]);
const query = Aggregation.defineQueryAggregation({ execute: (page) => pages.get(page) ?? [] });
console.log(query.collect([1, 2], undefined));

Add a primary key and retention policy to the same collect ​

Configuration · Node.js

ts
import { Aggregation } from '@jangts/agent-core/kits/aggregation';
type Row = { id: string; title: string };
const pages = new Map<number, Row[]>([[1, [{ id: 'a', title: '第一页' }]], [2, [{ id: 'a', title: '重复项' }, { id: 'b', title: '第二页' }]]]);
const query = Aggregation.defineQueryAggregation({
  execute: (page: number) => pages.get(page) ?? [],
  key: (row: Row) => row.id,
  merge: (row: Row, previous: Row | undefined) => previous ?? row,
});
console.log(query.collect([1, 2], undefined));
console.log(Aggregation.mergeByKey([...pages.values()].flat(), row => row.id, (row, previous) => previous ?? row));
js
import { Aggregation } from '@jangts/agent-core/kits/aggregation';
const pages = new Map([[1, [{ id: 'a', title: '第一页' }]], [2, [{ id: 'a', title: '重复项' }, { id: 'b', title: '第二页' }]]]);
const query = Aggregation.defineQueryAggregation({
    execute: (page) => pages.get(page) ?? [],
    key: (row) => row.id,
    merge: (row, previous) => previous ?? row,
});
console.log(query.collect([1, 2], undefined));
console.log(Aggregation.mergeByKey([...pages.values()].flat(), row => row.id, (row, previous) => previous ?? row));

Policies & implementations ​

API reference, usage examples and developer guides.