跳转到内容

Thing

Thing 类用于表示记录 ID

导入

import { Thing } from "@tai-kun/surrealdb/decodeonly-datatypes";
import { Thing } from "@tai-kun/surrealdb/encodable-datatypes";
import { Thing } from "@tai-kun/surrealdb/standard-datatypes";

.constructor()

创建一个新的 Thing 对象。

new Thing(source: [table: string, id: string | number | bigint | object]);
new Thing(table: string, id: string | number | bigint | object);

参数

source

记录 ID 的表名和 ID 部分的组合。

table

记录 ID 的表名部分。

id

记录 ID 的 ID 部分。

返回值

如果通过 new 关键字调用,Thing 将返回它的实例。

.table 实例 属性 >=decode-only

记录 ID 的表名部分。获取此属性时,字符串不会被转义。

.table: string;

例子

获取此属性时,字符串不会被转义。

import { Thing } from "@tai-kun/surrealdb/decodeonly-datatypes";
const thing = new Thing("foo-bar", 0);
console.log(this.id);
//-> foo-bar

.id 实例 属性 >=decode-only

记录 ID 的 ID 部分。

.id: string | number | bigint | object;

.toString() 实例 方法 >=encodable

Thing 对象转换为 SurrealQL 中可用的字符串表示形式。表名和 ID 部分将按照 SurrealDB 的实现方式进行转义和格式化。对象属性将按升序排序。

.valueOf().toJSON() 方法将返回与该方法相同的结果。

.toString(): string;

参数

无。

返回值

返回格式化后的记录 ID 字符串。

例子

import { Thing } from "@tai-kun/surrealdb/encodable-datatypes";
const thing = new Thing([
"foo-bar",
new Uuid("018fb2c0-7bb7-7fca-8308-b24d0be065dc"),
]);
console.log(thing.toString());
//-> ⟨foo-bar⟩:u'018fb2c0-7bb7-7fca-8308-b24d0be065dc'

.toSurql() 实例 方法 >=encodable

Thing 对象转换为可以嵌入 SurrealQL 的字符串。类似于 .toString(),但添加 r 前缀,以便查询解析器识别该字符串是记录 ID。

.toSurql(): string;

参数

无。

返回值

返回格式化后的记录 ID 字符串。

例子

import { Thing } from "@tai-kun/surrealdb/encodable-datatypes";
const thing = new Thing("foo", "bar");
console.log(thing.toSurql());
//-> r'foo:bar'

.clone() 实例 方法 =standard

复制 Thing 对象。但是,ID 部分不会被复制,而是被引用。

.clone(): this;

参数

无。

返回值

返回一个新的 Thing 对象。如果继承了 Thing 类,则返回该类的实例。

进阶

类型保护

可以使用类型参数来确保 Thing 的表名和 ID 部分的类型安全:

import { Thing, Uuid } from "@tai-kun/surrealdb/standard-datatypes";
function isUserRecordId(thing: unknown): thing is Thing<"user", Uuid> {
return thing instanceof Thing
&& thing.table === "user"
&& thing.id instanceof Uuid
}

通用 Thing 对象判断

建议使用 isThing 函数来判断值是否是 Thing 对象,而无需依赖预设。此函数不使用 instanceof,因此在验证值的预设不明确时非常有用。

import { isThing } from "@tai-kun/surrealdb";