Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify recordId to return a RecordId instance #65

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/genSchema/ensureRecordSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ export const ensureRecordSchema = async (rootPath: string) => {
const content = `import z from 'zod';
import { RecordId, StringRecordId } from 'surrealdb'

type TableRecordId<T extends string> = RecordId<T> | StringRecordId | \`\${T}:\${string}\`;

export function recordId<Table extends string = string>(table?: Table) {
const tableRegex = table ? table : '[A-Za-z_][A-Za-z0-9_]*';
const idRegex = '[^:]+';
Expand All @@ -26,12 +24,29 @@ export function recordId<Table extends string = string>(table?: Table) {
message: table
? \`Invalid record ID format. Must be '\${table}:id'\`
: "Invalid record ID format. Must be 'table:id'"
}),
z.object({
tb: z.string(),
id: z.union([z.string(), z.number(), z.record(z.unknown())])
}).refine((val) => !table || val.tb === table, {
message: table ? \`RecordId must be of type '\${table}'\` : undefined
})
]).transform((val): TableRecordId<Table> => {
]).transform((val): RecordId<Table> => {
if (val instanceof RecordId) {
return val as RecordId<Table>;
}
if (val instanceof StringRecordId) {
const [tb!, id!] = val.rid.split(':');
return new RecordId(tb, id) as RecordId<Table>;
}
if (typeof val === 'string') {
return new StringRecordId(val) as TableRecordId<Table>;
const [tb!, id!] = val.split(':');
return new RecordId(tb, id) as RecordId<Table>;
}
if (typeof val === 'object' && val !== null && 'tb' in val && 'id' in val) {
return new RecordId(val.tb, val.id) as RecordId<Table>;
}
return val as TableRecordId<Table>;
throw new Error('Invalid input for RecordId');
});
}`

Expand Down