|
| 1 | +import { writeFileSync, readFileSync } from 'fs'; |
| 2 | +import { join, resolve, dirname } from 'path'; |
| 3 | +import { Client } from 'notion-to-utils'; |
| 4 | +import dotenv from 'dotenv'; |
| 5 | +import { fileURLToPath } from 'url'; |
| 6 | + |
| 7 | +// ES 모듈에서 __dirname 대체 |
| 8 | +const __filename = fileURLToPath(import.meta.url); |
| 9 | +const __dirname = dirname(__filename); |
| 10 | + |
| 11 | +// 환경 변수 로드 |
| 12 | +dotenv.config({ path: resolve(__dirname, '../.env.local') }); |
| 13 | + |
| 14 | +// 페이지 ID |
| 15 | +const PAGE_ID = '1239c6bf-2b17-8076-a838-d17ca1c89783'; |
| 16 | + |
| 17 | +// ? using this script : pnpx tsx scripts/fetchNotionProperties.ts |
| 18 | +async function fetchAndSaveProperties() { |
| 19 | + try { |
| 20 | + // Notion API 키 확인 |
| 21 | + let apiKey = process.env.NOTION_API_KEY; |
| 22 | + |
| 23 | + // 환경 변수에서 API 키를 가져오지 못한 경우 .env.local 파일에서 직접 읽기 시도 |
| 24 | + if (!apiKey) { |
| 25 | + try { |
| 26 | + const envPath = resolve(__dirname, '../.env.local'); |
| 27 | + console.log( |
| 28 | + `환경 변수에서 API 키를 찾을 수 없어 ${envPath} 파일에서 직접 읽습니다.` |
| 29 | + ); |
| 30 | + const envContent = readFileSync(envPath, 'utf8'); |
| 31 | + const match = envContent.match(/NOTION_API_KEY=(.+)/); |
| 32 | + if (match && match[1]) { |
| 33 | + apiKey = match[1]; |
| 34 | + console.log('API 키를 파일에서 성공적으로 읽었습니다.'); |
| 35 | + } |
| 36 | + } catch (err) { |
| 37 | + console.error('.env.local 파일 읽기 실패:', err); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + if (!apiKey) { |
| 42 | + console.error( |
| 43 | + 'NOTION_API_KEY를 찾을 수 없습니다. .env.local 파일에 NOTION_API_KEY=your_key 형식으로 설정해주세요.' |
| 44 | + ); |
| 45 | + process.exit(1); |
| 46 | + } |
| 47 | + |
| 48 | + console.log('Notion API에서 페이지 속성 데이터를 가져오는 중...'); |
| 49 | + |
| 50 | + // Notion 클라이언트 생성 |
| 51 | + const client = new Client({ auth: apiKey }); |
| 52 | + |
| 53 | + // 페이지 속성 가져오기 |
| 54 | + const properties = await client.getPageProperties(PAGE_ID); |
| 55 | + |
| 56 | + // JSON 파일로 저장 |
| 57 | + const outputPath = join(__dirname, '../src/sample-data/notionTitle.json'); |
| 58 | + console.log(`저장 경로: ${outputPath}`); |
| 59 | + writeFileSync(outputPath, JSON.stringify(properties, null, 2), 'utf8'); |
| 60 | + |
| 61 | + console.log( |
| 62 | + `페이지 속성 데이터가 성공적으로 저장되었습니다: ${outputPath}` |
| 63 | + ); |
| 64 | + console.log( |
| 65 | + `총 ${Object.keys(properties || {}).length}개의 속성을 가져왔습니다.` |
| 66 | + ); |
| 67 | + } catch (error) { |
| 68 | + console.error('페이지 속성 데이터 가져오기 실패:', error); |
| 69 | + process.exit(1); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// 스크립트 실행 |
| 74 | +fetchAndSaveProperties(); |
0 commit comments