@hansolbangul/notion-api
Version:
A lightweight library for fetching and statically generating data and TypeScript types from Notion pages.
134 lines (129 loc) • 4.77 kB
JavaScript
;
var notionClient = require('notion-client');
var fs = require('fs');
var process = require('node:process');
var url = require('url');
var path = require('path');
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var process__namespace = /*#__PURE__*/_interopNamespaceDefault(process);
const notion = new notionClient.NotionAPI();
const __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('type-cli.cjs', document.baseURI).href)));
const __dirname$1 = path.dirname(__filename$1);
function loadEnv() {
const envPath = path.resolve(__dirname$1, '.env');
console.log('Resolved .env Path:', envPath); // 디버깅용 로그
if (fs.existsSync(envPath)) {
const envData = fs.readFileSync(envPath, 'utf8');
envData.split('\n').forEach((line) => {
const [key, value] = line.split('=').map((v) => v.trim());
if (key && value) {
process__namespace.env[key] = value;
}
});
}
else {
console.error('.env file not found at:', envPath);
process__namespace.exit(1);
}
}
loadEnv();
async function fetchSchema(pageId) {
const recordMap = await notion.getPage(pageId);
const collection = Object.values(recordMap.collection)[0]?.value;
const schema = collection?.schema;
if (!schema) {
throw new Error('Schema not found in the given Notion page.');
}
return schema;
}
function generateType(schema) {
let result = 'interface NotionProperties {\n';
for (const key in schema) {
const field = schema[key];
const fieldName = field.name;
const fieldType = field.type;
const type = (() => {
switch (fieldType) {
case 'title':
case 'text':
case 'url':
case 'email':
case 'phone_number':
return 'string';
case 'number':
return 'number';
case 'select':
return field.options
? `(${field.options.map((option) => `"${option.value}"`).join(' | ')})[]`
: 'string';
case 'multi_select':
return field.options
? `(${field.options
.map((option) => `"${option.value}"`)
.join(' | ')})[]`
: 'string[]';
case 'date':
return '{ type: string; start_date: string }';
case 'file':
return '{ url: string }[]';
case 'person':
return '{ id: string; name: string; profile_photo: string }[]';
case 'checkbox':
return 'boolean';
case 'created_time':
case 'last_edited_time':
case 'status':
return 'string';
default:
return 'unknown';
}
})();
result += ` ${fieldName}: ${type};\n`;
}
result += '}';
return result;
}
async function main() {
const args = process__namespace.env.pageId || process__namespace.argv.slice(1);
const pageId = typeof args === 'string' ? args : args[0];
if (!pageId) {
console.error('Error: Please provide a Notion page ID as the first argument.');
process__namespace.exit(1);
}
try {
console.log(`Fetching schema from Notion for page ID: ${pageId}...`);
const schema = await fetchSchema(pageId);
console.log('Generating TypeScript types...');
const types = generateType(schema);
console.log('Saving types to src/types.d.ts...');
fs.writeFileSync('./src/types.d.ts', types);
console.log('Type definitions generated successfully!');
}
catch (error) {
if (error instanceof Error) {
console.error(error.message);
}
else {
console.error('Unknown error', error);
}
}
}
main();
//# sourceMappingURL=type-cli.cjs.map