Skip to content

API 参考 ​

LiteIbatis ​

构造函数 ​

typescript
new LiteIbatis(options?: LiteIbatisOptions)

创建 lite-ibatis 实例。

typescript
import { LiteIbatis } from 'lite-ibatis';

const lite = new LiteIbatis();

parse ​

typescript
parse(source: string): Token[]

解析模板字符串为 Token 树。

参数:

  • source - 模板字符串

返回: Token 数组

typescript
const tokens = lite.parse(`$getUser:
  select * from users
  #if id
    where id = #{id}`);

compile ​

typescript
compile(tokens: Token[]): Compiled

编译 Token 树为可执行函数。

参数:

  • tokens - parse 返回的 Token 树

返回: Compiled 函数,签名为 (id: string, data?: any) => [string, any[]]

typescript
const run = lite.compile(tokens);
const [sql, params] = run('getUser', { id: 123 });

syntax ​

typescript
get syntax(): Syntax[]
set syntax(value: Syntax[])

获取或设置自定义语法插件。

typescript
// 获取内置语法
const syntaxes = lite.syntax;

// 设置自定义语法
lite.syntax = [...syntaxes, new MyCustomSyntax()];

类型定义 ​

Compiled ​

typescript
interface Compiled {
  (id: string, data?: any): [sql: string, params: any[]]
}

编译后的可执行函数。

Token ​

typescript
interface Token {
  indent: number;      // 缩进级别
  key: string;         // 语法类型
  value: string;       // 解析后的值
  source: string;      // 原始字符串
  children: Token[];   // 子节点
}

Syntax ​

typescript
interface Syntax {
  key: string;
  getEndIndex(input: string, start: number, indent: number): number;
  test(input: string, start: number): boolean;
  parse(input: string): Token;
  compile?(token: Token, next: CompileChildren): string;
}

自定义语法需要实现此接口。

架构 ​

工作流程 ​

模板字符串 ──► parse() ──► Token 树 ──► compile() ──► 可执行函数 ──► (id, data) ──► [sql, params]

组件 ​

组件职责
Lexer将字符串解析为 Token 树
Generator将 Token 树编译为 JS 代码(洋葱模型)
Executor执行生成的 JS 代码,返回结果
Syntax[]每种语法类型的解析和编译规则

洋葱模型 ​

每个 Syntax.compile(token, next) 可以调用 next(children) 处理子节点:

TextSyntax.compile() → next(children) → IfSyntax.compile() → next(children) → TextSyntax.compile()

这种设计使得每个语法都可以独立处理自己的逻辑,同时灵活控制子节点的处理方式。

最后更新: