statistiques/src/notion/publish/v2/publishStatsToPage.ts

98 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-09-05 09:23:27 +02:00
import { Client, isFullBlock } from "@notionhq/client";
import { BlockObjectRequest } from "@notionhq/client/build/src/api-endpoints";
import { formatValue } from "../../../format/formatValue";
import {
isStatGroupDesc,
StatDesc,
StatGroupDesc,
StatsType,
2024-09-17 13:54:59 +02:00
} from "../../../statistiques/v2/desc/StatsDesc";
2024-09-05 09:23:27 +02:00
import { listAllChildrenBlocks } from "../../utils/listAllChildrenBlocks";
import { removeBlocks } from "../../utils/removeBlocks";
export async function publishStatsToPage<D extends StatGroupDesc>(
notionClient: Client,
statsPageId: string,
descriptor: D,
stats: StatsType<D>
) {
const childrenBlocks = (
await listAllChildrenBlocks(notionClient, {
block_id: statsPageId,
})
).filter(isFullBlock);
const blocksIdsToRemove = childrenBlocks.map((b) => b.id);
await removeBlocks(notionClient, blocksIdsToRemove);
const newBlocks = createStatGroupChildrenListItemBlock(descriptor, stats);
await notionClient.blocks.children.append({
block_id: statsPageId,
children: [...newBlocks],
});
}
function createStatGroupListItemBlock<D extends StatGroupDesc>(
descriptor: D,
stats: StatsType<D>
): BulletedListItemBlockObjectRequest {
return {
bulleted_list_item: {
rich_text: [
{
text: {
content: descriptor.label,
},
},
],
children: createStatGroupChildrenListItemBlock(
descriptor,
stats
) as BulletedListItemChildren,
},
};
}
type BulletedListItemBlockObjectRequest = Extract<
BlockObjectRequest,
{ bulleted_list_item: object }
>;
type BulletedListItemChildren =
BulletedListItemBlockObjectRequest["bulleted_list_item"]["children"];
function createStatGroupChildrenListItemBlock<D extends StatGroupDesc>(
descriptor: D,
stats: StatsType<D>
): BulletedListItemBlockObjectRequest[] {
return Object.keys(descriptor.stats).map((statName) => {
const childStatDesc = descriptor.stats[statName];
const childStatValue = stats[statName];
return isStatGroupDesc(childStatDesc)
? createStatGroupListItemBlock(
childStatDesc,
childStatValue as StatsType<typeof childStatDesc>
)
: createStatListItemBlock(childStatDesc, childStatValue as number);
});
}
function createStatListItemBlock(
descriptor: StatDesc,
statValue: number
): BulletedListItemBlockObjectRequest {
return {
bulleted_list_item: {
rich_text: [
{
text: {
content:
descriptor.label + ": " + formatValue(statValue, descriptor),
},
},
],
},
};
}