Skip to content

src/download.ts

57 lines · 1.8 KB · TypeScript
Raw
/**
 * Download a Dropbox file as metadata plus base64-encoded bytes.
 * Pick this when you need the file contents, not just `./get-metadata`.
 *
 * @param params.path - Dropbox file path starting with `/`.
 * @returns `{ metadata, bytesBase64, byteLength, contentType }`.
 *
 * @example
 * import download from 'kody:@kentcdodds/dropbox/download'
 * const file = await download({ path: '/notes/todo.txt' })
 */

import { dropboxDownload } from './request.ts'
import type { DropboxRequestResult, JsonRecord } from './types.ts'
import { requireDropboxPath, requireRecord } from './types.ts'

export type DownloadInput = {
	path: string
}

export type DownloadBody = {
	metadata: JsonRecord | null
	bytesBase64: string
	byteLength: number
	contentType: string | null
}

/**
 * Download a Dropbox file as metadata plus base64-encoded bytes.
 * Pick this when you need the file contents, not just `./get-metadata`.
 *
 * @param params.path - Dropbox file path starting with `/`.
 * @returns `{ metadata, bytesBase64, byteLength, contentType }`.
 *
 * @example
 * import download from 'kody:@kentcdodds/dropbox/download'
 * const file = await download({ path: '/notes/todo.txt' })
 */
export async function download(input: DownloadInput): Promise<DownloadBody> {
	const path = requireDropboxPath(input.path)
	const result: DropboxRequestResult = await dropboxDownload({ path })
	return result.body as DownloadBody
}

/**
 * Download a Dropbox file and return metadata plus base64-encoded bytes.
 * @example
 * import download from 'kody:@kentcdodds/dropbox/download'
 * const file = await download({ path: '/notes/todo.txt' })
 */
export default async function downloadEntrypoint(
	params: Partial<DownloadInput> & Record<string, unknown> = {},
) {
	const input = requireRecord(params, 'download')
	requireDropboxPath(input.path)
	return download(input as unknown as DownloadInput)
}