Files
noco-auto/agents/noco/common/core.ts
2025-12-12 11:57:12 +08:00

99 lines
2.5 KiB
TypeScript

import { NocoApi } from "@kevisual/noco";
import { columns } from "../common/base-table.ts";
import { ColumnItem } from "./base-table.ts";
type ReponseData<T = {}> = {
code: number,
message?: string,
data?: T
}
export type CoreOptions<T = {}> = {
nocoApi: NocoApi,
baseId?: string
} & T
export class Core {
nocoApi: NocoApi;
#baseId?: string;
key = 'core';
title = '默认表';
description = '默认表描述';
#tableId?: string;
constructor(opts: {
nocoApi: NocoApi,
baseId?: string,
tableId?: string
}) {
this.nocoApi = opts.nocoApi;
this.baseId = opts.baseId;
this.tableId = opts.tableId;
}
get tableId() {
return this.#tableId;
}
set tableId(id: string | undefined) {
this.#tableId = id;
if (this.nocoApi.record && id) {
this.nocoApi.record.table = id;
}
}
get baseId() {
return this.#baseId;
}
set baseId(id: string | undefined) {
this.#baseId = id;
}
async createTable(opts?: { columns?: any[], title?: string, description?: string, baseId?: string }): Promise<ReponseData<{ id: string, title: string }>> {
const baseId = opts?.baseId ?? this.baseId!;
const title = opts?.title ?? this.title;
const description = opts?.description ?? this.description;
const _columns = opts?.columns ?? columns;
let tableId = '';
const res = await this.nocoApi.meta.tables.createTable(baseId, {
title,
description,
columns: _columns,
})
let code = 200;
if (res.code !== 200) {
const res = await this.nocoApi.meta.tables.list(baseId);
const list = res.data?.list || [];
const existTable = list.find(t => t.title === title);
if (existTable) {
tableId = existTable.id;
} else {
return {
code: res.code,
message: `创建表失败,且未找到同名表`,
}
}
} else {
tableId = res?.data?.id;
}
this.tableId = tableId;
if (this.nocoApi.record) {
this.nocoApi.record.table = tableId;
}
return {
code,
data: {
id: tableId,
title,
}
};
}
getItem(id: number): Promise<ReponseData<ColumnItem>> {
return this.nocoApi.record.read(id);
}
getList(params: any): Promise<ReponseData<{ list: ColumnItem[] }>> {
return this.nocoApi.record.list({
...params,
});
}
updateItem(data: Partial<ColumnItem>) {
return this.nocoApi.record.update(data);
}
createItem(data: Partial<ColumnItem>) {
return this.nocoApi.record.create(data);
}
}