Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kentcdodds/notion

src/append-block-children.ts

45 lines · 1.6 KB · TypeScript
import { notionRequest, type JsonRecord } from './request.ts'
import { inputRecord, optionalRecord, optionalString, requiredString } from './validation.ts'

type AppendBlockChildrenResponse = {
  results?: unknown[]
  [key: string]: unknown
}

/** Preview or append child blocks to a Notion page or block. */
export default async function appendBlockChildren(params: Record<string, unknown>) {
  const input = inputRecord(params)
  const blockId = requiredString(input, 'blockId')
  const children = input.children
  if (!Array.isArray(children) || children.length === 0) {
    throw new Error('children must be a non-empty array of Notion block objects.')
  }

  // position: { type: 'after_block', after_block: { id } } | { type: 'start' } | { type: 'end' }
  const payload: JsonRecord = {
    children,
    position: optionalRecord(input, 'position'),
  }
  const path = '/blocks/' + encodeURIComponent(blockId) + '/children'
  const account = optionalString(input, 'account')
  const integration = optionalString(input, 'integration')

  if (input.dryRun === true) {
    return { dryRun: true, method: 'PATCH', path, payload }
  }

  if (input.confirm !== true) {
    throw new Error('Appending Notion blocks requires confirm: true after explicit user approval of the destination and content. Use dryRun: true to preview.')
  }

  const result = await notionRequest<AppendBlockChildrenResponse>(path, {
    method: 'PATCH',
    body: payload,
    account,
    integration,
  })
  return {
    ok: true,
    appendedCount: Array.isArray(result.results) ? result.results.length : 0,
  }
}