UNPKG

@notionhq/client

Version:

A simple and easy to use client for the Notion API

258 lines 11.7 kB
import { BlockObjectResponse, CommentObjectResponse, DatabaseObjectResponse, DataSourceObjectResponse, DataSourceViewObjectResponse, EquationRichTextItemResponse, GroupFilterOperatorArray, ListDataSourceTemplatesResponse, MentionRichTextItemResponse, PageObjectResponse, PartialBlockObjectResponse, PartialCommentObjectResponse, PartialDatabaseObjectResponse, PartialDataSourceObjectResponse, PartialDataSourceViewObjectResponse, PartialPageObjectResponse, PartialUserObjectResponse, PropertyFilter, QueryDataSourceParameters, QueryDataSourceResponse, RichTextItemResponse, RichTextItemResponseCommon, TextRichTextItemResponse, TimestampFilter, UserObjectResponse } from "./api-endpoints"; import type Client from "./Client"; type PaginatedArgs = { start_cursor?: string | null; }; type PaginatedList<T> = { object: "list"; results: T[]; next_cursor: string | null; has_more: boolean; }; /** * Returns an async iterator over the results of any paginated Notion API. * * Example (given a notion Client called `notion`): * * ``` * for await (const block of iteratePaginatedAPI(notion.blocks.children.list, { * block_id: parentBlockId, * })) { * // Do something with block. * } * ``` * * @param listFn A bound function on the Notion client that represents a conforming paginated * API. Example: `notion.blocks.children.list`. * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent * calls to the API. Any necessary `next_cursor` will be automatically populated by * this function. Example: `{ block_id: "<my block id>" }` */ export declare function iteratePaginatedAPI<Args extends PaginatedArgs, Item>(listFn: (args: Args) => Promise<PaginatedList<Item>>, firstPageArgs: Args): AsyncIterableIterator<Item>; /** * Collect all of the results of paginating an API into an in-memory array. * * Example (given a notion Client called `notion`): * * ``` * const blocks = await collectPaginatedAPI(notion.blocks.children.list, { * block_id: parentBlockId, * }) * // Do something with blocks. * ``` * * @param listFn A bound function on the Notion client that represents a conforming paginated * API. Example: `notion.blocks.children.list`. * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent * calls to the API. Any necessary `next_cursor` will be automatically populated by * this function. Example: `{ block_id: "<my block id>" }` */ export declare function collectPaginatedAPI<Args extends PaginatedArgs, Item>(listFn: (args: Args) => Promise<PaginatedList<Item>>, firstPageArgs: Args): Promise<Item[]>; type DataSourceTemplate = ListDataSourceTemplatesResponse["templates"][number]; type ListDataSourceTemplatesArgs = PaginatedArgs & { data_source_id: string; name?: string; page_size?: number; }; /** * Returns an async iterator over data source templates. * * Example (given a notion Client called `notion`): * * ``` * for await (const template of iterateDataSourceTemplates(notion, { * data_source_id: dataSourceId, * })) { * console.log(template.name, template.is_default) * } * ``` * * @param client A Notion client instance. * @param args Arguments including the data_source_id and optional start_cursor. */ export declare function iterateDataSourceTemplates(client: Client, args: ListDataSourceTemplatesArgs): AsyncIterableIterator<DataSourceTemplate>; /** * Collect all data source templates into an in-memory array. * * Example (given a notion Client called `notion`): * * ``` * const templates = await collectDataSourceTemplates(notion, { * data_source_id: dataSourceId, * }) * // Do something with templates. * ``` * * @param client A Notion client instance. * @param args Arguments including the data_source_id and optional start_cursor. */ export declare function collectDataSourceTemplates(client: Client, args: ListDataSourceTemplatesArgs): Promise<DataSourceTemplate[]>; type DataSourceRow = QueryDataSourceResponse["results"][number]; /** * A filter the full-query helpers can combine with a created_time window bound. * * A top-level `or` filter is intentionally excluded: the helpers add a * created_time lower bound with `and`, and Notion only supports two levels of * filter nesting, so an `or` at the root leaves no room for the bound. Express * such queries as an `and` group, or run the helper once per `or` branch and * merge the results. */ export type FullDataSourceQueryFilter = PropertyFilter | TimestampFilter | { and: GroupFilterOperatorArray; }; /** * Arguments for the full-query helpers. The same as `dataSources.query`, minus * the fields the helper controls: `start_cursor` (pagination is automatic) and * `sorts` (the helper sorts by created_time to partition). `filter` is narrowed * to {@link FullDataSourceQueryFilter}. */ export type FullDataSourceQueryArgs = Omit<QueryDataSourceParameters, "start_cursor" | "sorts" | "filter"> & { filter?: FullDataSourceQueryFilter; }; /** * Iterate over every row of a data source, including rows past the per-query * result limit that `dataSources.query` enforces on large data sources. * * A single query (one filter and sort) returns at most a fixed number of rows * (10,000 by default). Once that limit is reached, `has_more` becomes `false` * and the response carries `request_status.type === "incomplete"`. Plain * pagination such as {@link iteratePaginatedAPI} stops there and silently * misses the rest of the data source. * * This helper works around the limit by partitioning the data source into * created_time windows. It sorts by created_time ascending; whenever a window * reaches the limit, it starts a fresh query from the last row's created_time. * Each fresh query has a different filter, so it gets its own result budget. * Rows that share a boundary timestamp are de-duplicated by id, so every row is * yielded exactly once. * * created_time is used because it never changes. last_edited_time would shift * rows between windows as they are edited, causing gaps or duplicates. * * Throws if a single created_time value holds more rows than the limit, since * the window cannot be narrowed by time alone. Add a filter in that case so * each window stays under the limit. * * Example (given a notion Client called `notion`): * * ``` * for await (const row of iterateAllDataSourceRows(notion, { * data_source_id: dataSourceId, * })) { * // Do something with row. * } * ``` * * @param client A Notion client instance. * @param args Query arguments. `start_cursor` and `sorts` are managed by the * helper; `filter` is combined with the created_time window bound. */ export declare function iterateAllDataSourceRows(client: Client, args: FullDataSourceQueryArgs): AsyncIterableIterator<DataSourceRow>; /** * Collect every row of a data source into an in-memory array, including rows * past the per-query result limit. See {@link iterateAllDataSourceRows} for how * the limit is handled. * * Before using this, check that the full data source fits in memory. For very * large data sources, prefer {@link iterateAllDataSourceRows} and process rows * as they stream. * * Example (given a notion Client called `notion`): * * ``` * const rows = await collectAllDataSourceRows(notion, { * data_source_id: dataSourceId, * }) * // Do something with rows. * ``` * * @param client A Notion client instance. * @param args Query arguments. See {@link iterateAllDataSourceRows}. */ export declare function collectAllDataSourceRows(client: Client, args: FullDataSourceQueryArgs): Promise<DataSourceRow[]>; type ObjectResponse = PageObjectResponse | PartialPageObjectResponse | DataSourceObjectResponse | PartialDataSourceObjectResponse | DatabaseObjectResponse | PartialDatabaseObjectResponse | BlockObjectResponse | PartialBlockObjectResponse; /** * @returns `true` if `response` is a full `BlockObjectResponse`. */ export declare function isFullBlock(response: ObjectResponse): response is BlockObjectResponse; /** * @returns `true` if `response` is a full `PageObjectResponse`. */ export declare function isFullPage(response: ObjectResponse): response is PageObjectResponse; /** * @returns `true` if `response` is a full `DataSourceObjectResponse`. */ export declare function isFullDataSource(response: ObjectResponse): response is DataSourceObjectResponse; /** * @returns `true` if `response` is a full `DatabaseObjectResponse`. */ export declare function isFullDatabase(response: ObjectResponse): response is DatabaseObjectResponse; /** * @returns `true` if `response` is a full `DataSourceObjectResponse` or a full * `PageObjectResponse`. * * Can be used on the results of the list response from `queryDataSource` or * `search` APIs. */ export declare function isFullPageOrDataSource(response: ObjectResponse): response is DataSourceObjectResponse | PageObjectResponse; /** * @returns `true` if `response` is a full `UserObjectResponse`. */ export declare function isFullUser(response: UserObjectResponse | PartialUserObjectResponse): response is UserObjectResponse; /** * @returns `true` if `response` is a full `CommentObjectResponse`. */ export declare function isFullComment(response: CommentObjectResponse | PartialCommentObjectResponse): response is CommentObjectResponse; /** * @returns `true` if `response` is a full `DataSourceViewObjectResponse`. */ export declare function isFullView(response: DataSourceViewObjectResponse | PartialDataSourceViewObjectResponse): response is DataSourceViewObjectResponse; /** * @returns `true` if `richText` is a `TextRichTextItemResponse`. */ export declare function isTextRichTextItemResponse(richText: RichTextItemResponse): richText is RichTextItemResponseCommon & TextRichTextItemResponse; /** * @returns `true` if `richText` is an `EquationRichTextItemResponse`. */ export declare function isEquationRichTextItemResponse(richText: RichTextItemResponse): richText is RichTextItemResponseCommon & EquationRichTextItemResponse; /** * @returns `true` if `richText` is an `MentionRichTextItemResponse`. */ export declare function isMentionRichTextItemResponse(richText: RichTextItemResponse): richText is RichTextItemResponseCommon & MentionRichTextItemResponse; /** * Extracts a Notion ID from a Notion URL or returns the input if it's already a valid ID. * * Prioritizes path IDs over query parameters to avoid extracting view IDs instead of database IDs. * * @param urlOrId A Notion URL or ID string * @returns The extracted UUID in standard format (with hyphens) or null if invalid * * @example * ```typescript * // Database URL with view ID - extracts database ID, not view ID * extractNotionId('https://notion.so/workspace/DB-abc123def456789012345678901234ab?v=viewid123') * // Returns: 'abc123de-f456-7890-1234-5678901234ab' (database ID) * * // Already formatted UUID * extractNotionId('12345678-1234-1234-1234-123456789abc') * // Returns: '12345678-1234-1234-1234-123456789abc' * ``` */ export declare function extractNotionId(urlOrId: string): string | null; /** * Extracts a database ID from a Notion database URL. * Convenience wrapper around `extractNotionId`. */ export declare function extractDatabaseId(databaseUrl: string): string | null; /** * Extracts a page ID from a Notion page URL. * Convenience wrapper around `extractNotionId`. */ export declare function extractPageId(pageUrl: string): string | null; /** * Extracts a block ID from a Notion URL with a block fragment. * Looks for #block-<id> or #<id> patterns. */ export declare function extractBlockId(urlWithBlock: string): string | null; export {}; //# sourceMappingURL=helpers.d.ts.map