2.8 KiB
discovery
(no submodules)
Purpose
Provides file-system-based schema discovery for SurrealDB schema files (.surql, .sql). Schema discovery is the first step of the database initialisation workflow: given a directory path, discoverSchemas enumerates matching files, orders them according to DEFAULT_SCHEMA_ORDER, and returns typed SchemaFile descriptors. The filterSchemas and getSchemasToLoad helpers compose discovery with predicate filtering for conditional loading (e.g. skipping seed files in production).
Features
getDefaultSchemaDir()— returns conventional./db/schemapathdiscoverSchemas()— enumerates.surql/.sqlfiles, optionally recursivesortSchemaFiles()— orders files byDEFAULT_SCHEMA_ORDERthen alphabeticallyfilterSchemas()— applies aSchemaFilterpredicate to a file listgetSchemasToLoad()— discovery + filtering in one callreadSchemaContent()— reads file content with caching of pre-populatedcontentfield
Usage: Basic Example
import { discoverSchemas, readSchemaContent } from "@suaveplan/surrealdb/schema/discovery";
const files = await discoverSchemas("./db/schema");
for (const file of files) {
const content = await readSchemaContent(file);
console.log(file.name, content.length, "bytes");
}
Usage: Advanced Example
import { getSchemasToLoad } from "@suaveplan/surrealdb/schema/discovery";
const schemas = await getSchemasToLoad(
"./db/schema",
(f) => !f.name.includes("seed"), // skip seeds in production
{ extensions: [".surql"], recursive: true }
);
API Reference
getDefaultSchemaDir(): string
Returns path.join(process.cwd(), "db", "schema").
discoverSchemas(dir, options?): Promise<SchemaFile[]>
Reads dir for files with matching extensions. Returns sorted SchemaFile[].
Throws: SurrealError(SURREAL.SCHEMA_LOAD_FAILED) if directory read fails.
sortSchemaFiles(files): SchemaFile[]
Pure. Orders by DEFAULT_SCHEMA_ORDER membership then lexicographically.
filterSchemas(files, filter): SchemaFile[]
Pure. Returns files.filter(filter).
getSchemasToLoad(dir, filter?, options?): Promise<SchemaFile[]>
Combines discoverSchemas and filterSchemas.
readSchemaContent(file): Promise<string>
Returns file.content if set, otherwise reads from file.path.
Throws: SurrealError(SURREAL.SCHEMA_LOAD_FAILED) on read failure.
Implementation Notes
Schema ordering uses DEFAULT_SCHEMA_ORDER from the constants module. Files matching known schema names ("schema", "tables", "indexes", etc.) are placed first in that order; unrecognised names follow alphabetically. This matches the conventional SurrealDB schema application order where table definitions must precede index definitions.