Skip to content

Commit

Permalink
Create spent_on_food.js
Browse files Browse the repository at this point in the history
  • Loading branch information
lesnolie committed Mar 29, 2023
1 parent b3d5673 commit e0118cb
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions spent_on_food.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const today = new Date();
const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);

const { Client } = require('@notionhq/client');

const databaseId = process.env.NOTION_DATABASE_ID;
const apiKey = process.env.NOTION_API_KEY;

const notion = new Client({ auth: apiKey });

async function fetchAllPages(databaseId) {
let allResults = [];
let hasNextPage = true;
let startCursor = null;

while (hasNextPage) {
try {
const requestOptions = {
database_id: databaseId,
filter: {
and: [
{
property: '时间',
date: {
on_or_after: firstDayOfMonth.toISOString(),
before: lastDayOfMonth.toISOString()
}
},
{
property: '类目',
select: {
equals: '餐饮'
}
}
]
}
};
if (startCursor) {
requestOptions.start_cursor = startCursor;
}
const response = await notion.databases.query(requestOptions);

const data = response;
console.log('Current response data:', data);

if (data.results) {
console.log('Current page results:', data.results);
allResults.push(...data.results);
}
hasNextPage = data.has_more;
startCursor = data.next_cursor;
} catch (error) {
console.log('Error in request:', error);
}
}

return allResults;
}

async function main() {
const pages = await fetchAllPages(databaseId);
console.log('Pages fetched:', pages);

const foodAmount = pages.reduce((acc, page) => {
const priceProperty = Object.entries(page.properties).find(([key, value]) => key === "价格");
const price = priceProperty ? (priceProperty[1].number !== null ? priceProperty[1].number : 0) : 0;
console.log('Price:', price);
return acc + price;
}, 0);

console.log('Total amount spent on food:', foodAmount);
}

main();

0 comments on commit e0118cb

Please sign in to comment.