Created
July 28, 2022 09:08
-
-
Save mnmly/b55a45e4d71da8e3038f503b8340aafa to your computer and use it in GitHub Desktop.
notion's api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Client } = require("@notionhq/client") | |
const fs = require('fs') | |
const path = require( 'path' ) | |
const parse = require('url').parse | |
const request = require( 'request' ) | |
// Initializing a client | |
const download = (uri, filename, callback) => { | |
request.head(uri, (err, res, body) => { | |
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback); | |
}) | |
}; | |
const notion = new Client({ auth: process.env.NOTION_TOKEN }) | |
;( async () => { | |
const databaseId = '91de1f46495540e78a6e28bfee758925' | |
const myPage = await notion.databases.query({ | |
database_id: databaseId, | |
filter: { | |
property: "Primary", | |
multi_select: { | |
contains: 'Tracker' | |
} | |
} | |
}) | |
let rows = myPage.results.map( async (page) => { | |
let row = [] | |
const items = await notion.pages.properties.retrieve({ page_id: page.id, property_id: 'title'}) | |
const blockList = await notion.blocks.children.list({block_id: page.id}) | |
if ( items.results.length > 0 ) { | |
row[0] = items.results[0].title.text.content | |
} | |
if ( blockList.results.length > 0 ) { | |
let images = blockList.results.filter( (block) => { | |
return block.type == 'image' | |
} ).map( ( block, i ) => { | |
let url = block.image.file.url | |
let parsed = parse(url) | |
let components = parsed.pathname.split('/') | |
let folder = path.join('.', databaseId, components[components.length - 2]) | |
let filename = components[components.length - 1] | |
let destination = path.join(folder, filename) | |
if (!fs.existsSync(folder)){ | |
fs.mkdirSync(folder, { recursive: true }); | |
} | |
row[i + 1] = destination | |
download( url, destination, (err) => { | |
if (err) console.log(err) | |
} ) | |
}) | |
} | |
return row | |
}) | |
Promise.all(rows).then( (results) => { | |
fs.writeFile('demo.json', JSON.stringify(results.map( ( row ) => { | |
let images = [] | |
for (let i = 1; i < row.length; i ++ ) { images.push( row[ i ] ) } | |
return { | |
title: row[ 0 ], | |
images: images | |
} | |
} )), 'utf-8', (err) => { | |
console.log(err) | |
}) | |
}) | |
}) (); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment