{"_id":"@2sync/notion-sdk-js","name":"@2sync/notion-sdk-js","dist-tags":{"latest":"2.2.16"},"versions":{"2.2.16":{"name":"@2sync/notion-sdk-js","version":"2.2.16","description":"A simple and easy to use client for the Notion API","engines":{"node":">=12"},"homepage":"https://developers.notion.com/docs/getting-started","bugs":{"url":"https://github.com/makenotion/notion-sdk-js/issues"},"repository":{"type":"git","url":"git+https://github.com/makenotion/notion-sdk-js.git"},"keywords":["notion","notionapi","rest","notion-api"],"main":"./build/src","types":"./build/src/index.d.ts","scripts":{"prepare":"npm run build","prepublishOnly":"npm run checkLoggedIn && npm run lint && npm run test","build":"tsc","prettier":"prettier --write .","lint":"prettier --check . && eslint . --ext .ts && cspell '**/*' ","test":"jest ./test","check-links":"git ls-files | grep md$ | xargs -n 1 markdown-link-check","prebuild":"npm run clean","clean":"rm -rf ./build","checkLoggedIn":"./scripts/verifyLoggedIn.sh"},"author":"","license":"MIT","dependencies":{"@types/node-fetch":"^2.5.10","node-fetch":"^2.6.1"},"devDependencies":{"@types/jest":"^28.1.4","@typescript-eslint/eslint-plugin":"^5.39.0","@typescript-eslint/parser":"^5.39.0","cspell":"^5.4.1","eslint":"^7.24.0","jest":"^28.1.2","markdown-link-check":"^3.8.7","prettier":"^2.8.8","ts-jest":"^28.0.5","typescript":"^4.8.4"},"_id":"@2sync/notion-sdk-js@2.2.16","gitHead":"ac575c6a35192dad6dfeeb527de641442fbb8fa7","_nodeVersion":"20.17.0","_npmVersion":"10.8.2","dist":{"integrity":"sha512-GuZAn/2tAHrVuii6rjjQxNJeDSt9uo/TQaWuVXi1X4u9mVOzFIrsU4IoatOHSlmQltDfc+iTTwyuhNFJAFjpeg==","shasum":"712af73670480ed37b784bf4696507a63a5514cf","tarball":"https://registry.npmjs.org/@2sync/notion-sdk-js/-/notion-sdk-js-2.2.16.tgz","fileCount":40,"unpackedSize":980484,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIGfmpmL2J5closBE5er6jbjudpo3FcHMtyUVh7jvD650AiEAvoo6WKfXpEdkM6/I3r8CEFy1pYCtnoTIXM/vXIBHxcU="}]},"_npmUser":{"name":"melalj","email":"simo+npm@elalj.com"},"directories":{},"maintainers":[{"name":"melalj","email":"simo+npm@elalj.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/notion-sdk-js_2.2.16_1729259365944_0.32580833748459126"},"_hasShrinkwrap":false}},"time":{"created":"2024-10-18T13:49:25.849Z","2.2.16":"2024-10-18T13:49:26.123Z","modified":"2024-10-18T13:49:26.392Z"},"maintainers":[{"name":"melalj","email":"simo+npm@elalj.com"}],"description":"A simple and easy to use client for the Notion API","homepage":"https://developers.notion.com/docs/getting-started","keywords":["notion","notionapi","rest","notion-api"],"repository":{"type":"git","url":"git+https://github.com/makenotion/notion-sdk-js.git"},"bugs":{"url":"https://github.com/makenotion/notion-sdk-js/issues"},"license":"MIT","readme":"<div align=\"center\">\n\t<h1>Notion SDK for JavaScript</h1>\n\t<p>\n\t\t<b>A simple and easy to use client for the <a href=\"https://developers.notion.com\">Notion API</a></b>\n\t</p>\n\t<br>\n</div>\n\n![Build status](https://github.com/makenotion/notion-sdk-js/actions/workflows/ci.yml/badge.svg)\n[![npm version](https://badge.fury.io/js/%40notionhq%2Fclient.svg)](https://www.npmjs.com/package/@notionhq/client)\n\n## Installation\n\n```\nnpm install @notionhq/client\n```\n\n## Usage\n\n> Use Notion's [Getting Started Guide](https://developers.notion.com/docs/getting-started) to get set up to use Notion's API.\n\nImport and initialize a client using an **integration token** or an OAuth **access token**.\n\n```js\nconst { Client } = require(\"@notionhq/client\")\n\n// Initializing a client\nconst notion = new Client({\n  auth: process.env.NOTION_TOKEN,\n})\n```\n\nMake a request to any Notion API endpoint.\n\n> See the complete list of endpoints in the [API reference](https://developers.notion.com/reference).\n\n```js\n;(async () => {\n  const listUsersResponse = await notion.users.list({})\n})()\n```\n\nEach method returns a `Promise` which resolves the response.\n\n```js\nconsole.log(listUsersResponse)\n```\n\n```\n{\n  results: [\n    {\n      object: 'user',\n      id: 'd40e767c-d7af-4b18-a86d-55c61f1e39a4',\n      type: 'person',\n      person: {\n        email: 'avo@example.org',\n      },\n      name: 'Avocado Lovelace',\n      avatar_url: 'https://secure.notion-static.com/e6a352a8-8381-44d0-a1dc-9ed80e62b53d.jpg',\n    },\n    ...\n  ]\n}\n```\n\nEndpoint parameters are grouped into a single object. You don't need to remember which parameters go in the path, query, or body.\n\n```js\nconst myPage = await notion.databases.query({\n  database_id: \"897e5a76-ae52-4b48-9fdf-e71f5945d1af\",\n  filter: {\n    property: \"Landmark\",\n    rich_text: {\n      contains: \"Bridge\",\n    },\n  },\n})\n```\n\n### Handling errors\n\nIf the API returns an unsuccessful response, the returned `Promise` rejects with a `APIResponseError`.\n\nThe error contains properties from the response, and the most helpful is `code`. You can compare `code` to the values in the `APIErrorCode` object to avoid misspelling error codes.\n\n```js\nconst { Client, APIErrorCode } = require(\"@notionhq/client\")\n\ntry {\n  const notion = new Client({ auth: process.env.NOTION_TOKEN })\n  const myPage = await notion.databases.query({\n    database_id: databaseId,\n    filter: {\n      property: \"Landmark\",\n      rich_text: {\n        contains: \"Bridge\",\n      },\n    },\n  })\n} catch (error) {\n  if (error.code === APIErrorCode.ObjectNotFound) {\n    //\n    // For example: handle by asking the user to select a different database\n    //\n  } else {\n    // Other error handling code\n    console.error(error)\n  }\n}\n```\n\n### Logging\n\nThe client emits useful information to a logger. By default, it only emits warnings and errors.\n\nIf you're debugging an application, and would like the client to log response bodies, set the `logLevel` option to `LogLevel.DEBUG`.\n\n```js\nconst { Client, LogLevel } = require(\"@notionhq/client\")\n\nconst notion = new Client({\n  auth: process.env.NOTION_TOKEN,\n  logLevel: LogLevel.DEBUG,\n})\n```\n\nYou may also set a custom `logger` to emit logs to a destination other than `stdout`. A custom logger is a function which is called with 3 parameters: `logLevel`, `message`, and `extraInfo`. The custom logger should not return a value.\n\n### Client options\n\nThe `Client` supports the following options on initialization. These options are all keys in the single constructor parameter.\n\n| Option      | Default value              | Type         | Description                                                                                                                                                  |\n| ----------- | -------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `auth`      | `undefined`                | `string`     | Bearer token for authentication. If left undefined, the `auth` parameter should be set on each request.                                                      |\n| `logLevel`  | `LogLevel.WARN`            | `LogLevel`   | Verbosity of logs the instance will produce. By default, logs are written to `stdout`.                                                                       |\n| `timeoutMs` | `60_000`                   | `number`     | Number of milliseconds to wait before emitting a `RequestTimeoutError`                                                                                       |\n| `baseUrl`   | `\"https://api.notion.com\"` | `string`     | The root URL for sending API requests. This can be changed to test with a mock server.                                                                       |\n| `logger`    | Log to console             | `Logger`     | A custom logging function. This function is only called when the client emits a log that is equal or greater severity than `logLevel`.                       |\n| `agent`     | Default node agent         | `http.Agent` | Used to control creation of TCP sockets. A common use is to proxy requests with [`https-proxy-agent`](https://github.com/TooTallNate/node-https-proxy-agent) |\n\n### TypeScript\n\nThis package contains type definitions for all request parameters and responses,\nas well as some useful sub-objects from those entities.\n\nBecause errors in TypeScript start with type `any` or `unknown`, you should use\nthe `isNotionClientError` type guard to handle them in a type-safe way. Each\n`NotionClientError` type is uniquely identified by its `error.code`. Codes in\nthe `APIErrorCode` enum are returned from the server. Codes in the\n`ClientErrorCode` enum are produced on the client.\n\n```ts\ntry {\n  const response = await notion.databases.query({\n    /* ... */\n  })\n} catch (error: unknown) {\n  if (isNotionClientError(error)) {\n    // error is now strongly typed to NotionClientError\n    switch (error.code) {\n      case ClientErrorCode.RequestTimeout:\n        // ...\n        break\n      case APIErrorCode.ObjectNotFound:\n        // ...\n        break\n      case APIErrorCode.Unauthorized:\n        // ...\n        break\n      // ...\n      default:\n        // you could even take advantage of exhaustiveness checking\n        assertNever(error.code)\n    }\n  }\n}\n```\n\n#### Type guards\n\nThere are several [type guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types)\nprovided to distinguish between full and partial API responses.\n\n| Type guard function    | Purpose                                                                                |\n| ---------------------- | -------------------------------------------------------------------------------------- |\n| `isFullPage`           | Determine whether an object is a full `PageObjectResponse`                             |\n| `isFullBlock`          | Determine whether an object is a full `BlockObjectResponse`                            |\n| `isFullDatabase`       | Determine whether an object is a full `DatabaseObjectResponse`                         |\n| `isFullPageOrDatabase` | Determine whether an object is a full `PageObjectResponse` or `DatabaseObjectResponse` |\n| `isFullUser`           | Determine whether an object is a full `UserObjectResponse`                             |\n| `isFullComment`        | Determine whether an object is a full `CommentObjectResponse`                          |\n\nHere is an example of using a type guard:\n\n```typescript\nconst fullOrPartialPages = await notion.databases.query({\n  database_id: \"897e5a76-ae52-4b48-9fdf-e71f5945d1af\",\n})\nfor (const page of fullOrPartialPages.results) {\n  if (!isFullPageOrDatabase(page)) {\n    continue\n  }\n  // The page variable has been narrowed from\n  //      PageObjectResponse | PartialPageObjectResponse | DatabaseObjectResponse | PartialDatabaseObjectResponse\n  // to\n  //      PageObjectResponse | DatabaseObjectResponse.\n  console.log(\"Created at:\", page.created_time)\n}\n```\n\n### Utility functions\n\nThis package also exports a few utility functions that are helpful for dealing with\nany of our paginated APIs.\n\n#### `iteratePaginatedAPI(listFn, firstPageArgs)`\n\nThis utility turns any paginated API into an async iterator.\n\n**Parameters:**\n\n- `listFn`: Any function on the Notion client that represents a paginated API (i.e. accepts\n  `start_cursor`.) Example: `notion.blocks.children.list`.\n- `firstPageArgs`: Arguments that should be passed to the API on the first and subsequent calls\n  to the API, for example a `block_id`.\n\n**Returns:**\n\nAn [async iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)\nover results from the API.\n\n**Example:**\n\n```javascript\nfor await (const block of iteratePaginatedAPI(notion.blocks.children.list, {\n  block_id: parentBlockId,\n})) {\n  // Do something with block.\n}\n```\n\n#### `collectPaginatedAPI(listFn, firstPageArgs)`\n\nThis utility accepts the same arguments as `iteratePaginatedAPI`, but collects\nthe results into an in-memory array.\n\nBefore using this utility, check that the data you are dealing with is\nsmall enough to fit in memory.\n\n**Parameters:**\n\n- `listFn`: Any function on the Notion client that represents a paginated API (i.e. accepts\n  `start_cursor`.) Example: `notion.blocks.children.list`.\n- `firstPageArgs`: Arguments that should be passed to the API on the first and subsequent calls\n  to the API, for example a `block_id`.\n\n**Returns:**\n\nAn array with results from the API.\n\n**Example:**\n\n```javascript\nconst blocks = await collectPaginatedAPI(notion.blocks.children.list, {\n  block_id: parentBlockId,\n})\n// Do something with blocks.\n```\n\n## Requirements\n\nThis package supports the following minimum versions:\n\n- Runtime: `node >= 12`\n- Type definitions (optional): `typescript >= 4.5`\n\nEarlier versions may still work, but we encourage people building new applications to upgrade to the current stable.\n\n## Getting help\n\nIf you want to submit a feature request for Notion's API, or are experiencing any issues with the API platform, please email us at `developers@makenotion.com`.\n\nTo report issues with the SDK, it is possible to [submit an issue](https://github.com/makenotion/notion-sdk-js/issues) to this repo. However, we don't monitor these issues very closely. We recommend you reach out to us at `developers@makenotion.com` instead.\n","readmeFilename":"README.md"}