npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

notion-query

v1.0.2

Published

Just a small package for easily querying data from a Notion inline database.

Downloads

9

Readme

notion-query

notion-query is a lightweight package designed to simplify the process of dynamically querying data from Notion's inline databases. It provides an abstraction layer over the official @notionhq/client, making it easier to interact with various inline databases, regardless of their unique structures.

Features

  • Dynamic Queries: Handle different inline database structures without hardcoding.
  • Schema Abstraction: Define and manage database schemas easily.
  • Top-Level Page Management: Retrieve all top-level pages connected to your Notion integration.
  • Built on Official Client: Utilizes @notionhq/client for reliable Notion API interactions.

Installation

Install via npm or yarn or pnpm or bun:

bun i notion-query @notionhq/client

Quick Start

Setup

Initialize the official Notion client:

import { Client } from '@notionhq/client';

// Initialize Notion client with your integration token
export const notion = new Client({
    auth: process.env.NOTION_TOKEN,
});

Define Schema

Create a schema for your target inline database:

import { notion, NotionSchema } from 'notion-query';

const notionSchema = new NotionSchema(notion);

const guidePostTable = (databaseId: string) => {
    return notionSchema.db(databaseId).properties({
        Name: notionSchema.property_type('title').key(true),
        Country: notionSchema.property_type('relation').fetchRelated(true),
        Tags: notionSchema.property_type('multi_select').key(),

        CreatedBy: notionSchema
            .property_type('created_by')
            .include('name', 'email'),
        UpdatedBy: notionSchema
            .property_type('last_edited_by')
            .include('name', 'email'),
        CreatedAt: notionSchema.property_type('created_time').key(),
        UpdatedAt: notionSchema.property_type('last_edited_time').key(),
    });
};

Fetch Data

Retrieve and query data from Notion:

async function main() {
    try {
        // Get all top-level pages
        const pages = await notionSchema.getAllTopLevelPages();
        const inlineDBLists: inlineDB[] = [];

        // Fetch inline databases from each page
        for (const page of pages) {
            const dbLists = await notionSchema.getInlineDatabasesFromPage(page.page_id);
            inlineDBLists.push(...dbLists);
        }

        // Find the 'GuidePost' database ID
        const databaseID = inlineDBLists.find(db => db.databaseName === 'GuidePost')?.databaseId;

        if (!databaseID) {
            throw new Error("GuidePost database not found.");
        }

        // Query the database
        const data = await notionSchema.queryDatabase(guidePostTable(databaseID));
        console.log('Fetched data:', JSON.stringify(data, null, 2));
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

Example

Here's a complete example combining setup, schema definition, and data fetching:

import { Client } from '@notionhq/client';
import { notion, NotionSchema } from 'notion-query';

// Initialize Notion client
export const notionClient = new Client({
    auth: process.env.NOTION_TOKEN,
});

// Initialize NotionSchema
const notionSchema = new NotionSchema(notionClient);

// Define the schema for the 'GuidePost' database
const guidePostTable = (databaseId: string) => {
    return notionSchema.db(databaseId).properties({
        Name: notionSchema.property_type('title').key(true),
        Country: notionSchema.property_type('relation').fetchRelated(true),
        Tags: notionSchema.property_type('multi_select').key(),

        CreatedBy: notionSchema
            .property_type('created_by')
            .include('name', 'email'),
        UpdatedBy: notionSchema
            .property_type('last_edited_by')
            .include('name', 'email'),
        CreatedAt: notionSchema.property_type('created_time').key(),
        UpdatedAt: notionSchema.property_type('last_edited_time').key(),
    });
};

// Main function to fetch and display data
async function main() {
    try {
        const pages = await notionSchema.getAllTopLevelPages();
        const inlineDBLists: inlineDB[] = [];

        for (const page of pages) {
            const dbLists = await notionSchema.getInlineDatabasesFromPage(page.page_id);
            inlineDBLists.push(...dbLists);
        }

        const databaseID = inlineDBLists.find(db => db.databaseName === 'GuidePost')?.databaseId;

        if (!databaseID) {
            throw new Error("GuidePost database not found.");
        }

        const data = await notionSchema.queryDatabase(guidePostTable(databaseID));
        console.log('Fetched data:', JSON.stringify(data, null, 2));
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

Usage Notes

  • Ensure your Notion integration has access to the necessary pages and databases.

  • Customize the schema definitions based on your database properties.

Contributing

Feel free to open issues or submit pull requests for improvements and new features.

License

MIT © zed