@pagenote/notion-database
Version:
make notion as a real-database for server
106 lines • 3.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineNotionPropertySchemaByData = exports.getNotionTypeFromData = exports.resolveNotionRichTextItemRequest = void 0;
const notionType_1 = require("../types/notionType");
const index_1 = require("./index");
const base_1 = require("../types/base");
/**
* 将notion富文本,转为纯字符串
* [{plain_text:"a"},{plain_text:"a"}] -> ab
*/
function resolveNotionRichTextItemRequest(inputs) {
return inputs
.map(function (item) {
return item.plain_text;
})
.join('');
}
exports.resolveNotionRichTextItemRequest = resolveNotionRichTextItemRequest;
/**
* 根据js 数据类型返回notion type
* 1 -> number
* "1" -> rich_text
* false -> checkbox
*/
function getNotionTypeFromData(data) {
switch (typeof data) {
case 'boolean':
return notionType_1.SupportNotionTypes.checkbox;
case 'number':
return notionType_1.SupportNotionTypes.number;
case 'object':
if (Array.isArray(data)) {
if (data[0] instanceof Date) {
return notionType_1.SupportNotionTypes.date;
}
return notionType_1.SupportNotionTypes.multi_select;
}
else if (data instanceof Date) {
return notionType_1.SupportNotionTypes.date;
}
else {
return notionType_1.SupportNotionTypes.rich_text;
}
case 'string':
const isSelect = data.split('|');
if (isSelect.length > 1) {
return notionType_1.SupportNotionTypes.select;
}
else if (/^http/.test(data)) {
return notionType_1.SupportNotionTypes.url;
}
else {
return notionType_1.SupportNotionTypes.rich_text;
}
default:
return notionType_1.SupportNotionTypes.rich_text;
}
}
exports.getNotionTypeFromData = getNotionTypeFromData;
/**
* 通过js对象,推断出 notion 官方的properties schema定义
* {age:10,name:"username",signed: false} ==> {age:{type: number}, name:{type:"rich_text"}, signed: {type: "checkbox"}}
*/
function defineNotionPropertySchemaByData(data, setPrimaryKey = true) {
var _a;
const result = {};
for (let i in data) {
const tempValue = data[i];
// 推断的notion 类型
let dataType;
// js 传入对象已明确指定类型时,直接使用使用方的类型指定
if (notionType_1.supportNotionTypesArray.includes(tempValue)) {
dataType = tempValue;
}
else {
// 未显示定义的情况下,通过数值推断出类型
dataType = getNotionTypeFromData(tempValue);
}
// 不支持的notion类型,过滤此字段
if (!index_1.default[dataType]) {
console.error('un support notion type', dataType);
continue;
}
result[i] = (_a = index_1.default[dataType]) === null || _a === void 0 ? void 0 : _a.initPropertySchema(i);
}
// 指定notion的主键(title类型)
if (setPrimaryKey) {
let hasPrimaryKey = false;
for (let j in result) {
if (result[j].type === notionType_1.SupportNotionTypes.title) {
hasPrimaryKey = true;
break;
}
}
// 若无notion主键,新增字段
if (!hasPrimaryKey) {
result[base_1.NOTION_RESERVED_KEY] = {
title: {},
type: notionType_1.SupportNotionTypes.title
};
}
}
return result;
}
exports.defineNotionPropertySchemaByData = defineNotionPropertySchemaByData;
//# sourceMappingURL=util.js.map