Files
yc-modular-extractor-archived/lib/schemas.ts
T
2026-11-05 01:04:53 +08:00

10 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {mkdir,readFile,readdir} from 'node:fs/promises';
import path from 'node:path';
import {root,atomic,dir} from './store';
import {buildSchema,Field,InputError} from './schema';
export type SavedSchema={id:string;name:string;fields:Field[];schema:any;createdAt:string;updatedAt:string;version:number};
export function schemaPath(id:string){dir(id);return path.join(root,'schemas',id+'.json');}
export async function getSchema(id:string):Promise<SavedSchema>{return JSON.parse(await readFile(schemaPath(id),'utf8'));}
export async function listSchemas(){await mkdir(path.join(root,'schemas'),{recursive:true});const files=await readdir(path.join(root,'schemas'));return (await Promise.all(files.filter(f=>f.endsWith('.json')).map(f=>getSchema(f.slice(0,-5))))).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt));}
export async function putSchema(id:string,body:any,previous?:SavedSchema){if(typeof body?.name!=='string'||!body.name.trim()||body.name.length>120)throw new InputError('name 必须是 1–120 字符的名称');const schema=buildSchema(body.fields);const time=new Date().toISOString();const saved:SavedSchema={id,name:body.name.trim(),fields:body.fields,schema,createdAt:previous?.createdAt||time,updatedAt:time,version:(previous?.version||0)+1};await mkdir(path.join(root,'schemas'),{recursive:true});await atomic(schemaPath(id),saved);return saved;}