Skip to content

toSurql

The toSurql function converts JavaScript values into SurrealQL strings.

Import

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

Usage

function toSurql(value: unknown): string;

Arguments

value

A JavaScript value. It accepts one of the following types:

  • string
  • number
  • bigint
  • boolean
  • undefined
  • null
  • { toSurql(): string }
  • Date
  • { toJSON(): string }
  • unknown[]
  • { [key: string]: unknown }
  • Set<unknown>
  • Map<unknown, unknown>

unknown represents a value composed of the above types.

The conversion prioritizes the types in the order listed above. That is, if a plain object has both a .toJSON and a .toSurql function, the .toSurql function will be used.

Plain object detection uses is-plain-obj. Therefore, if a plain object does not have .toSurql or .toJSON, and has Symbol.toStringTag or Symbol.iterator, it will not be treated as an object, and an error will be thrown.

Return Value

A SurrealQL string.

Example

import { toSurql } from "@tai-kun/surrealdb/utils";
const surql = toSurql({
bigint: 9007199254740992n, // Number.MAX_SAFE_INTEGER + 1
boolean: [true, false],
date: new Date("2024-06-01T12:34:56.789Z"),
map: new Map([
[0, {
toJSON: () => [0, 1],
}],
]),
null: null,
number: 123,
set: new Set([{
toSurql: () => `<bytes>"hello"`,
}]),
string: "文字列",
undefined: undefined,
});
console.log(surql);

Output:

{bigint:9007199254740992,boolean:[true,false],date:d'2024-06-01T12:34:56.789Z',map:{0:[0,1]},null:NULL,number:123,set:[<bytes>"hello"],string:'文字列',undefined:NONE}