sebastianwessel / surrealdb-client-generator

Tool which generates a typescript client for SurrealDB and zod schema of a given database
MIT License
76 stars 12 forks source link

Improve record handling #25

Closed sebastianwessel closed 4 months ago

sebastianwessel commented 4 months ago

Improve handling of record links

CiskaLV commented 4 months ago

You could try making a RecordId Custom schema for zod i have been using this one i found

export const ZRecordIdInstanceOf = z.instanceof(RecordId);

export function recordId<Table extends string = string>(table?: Table) {
  return z.custom<RecordId<`${Table}`>>(
    val => {
      const instanceOfCheck = ZRecordIdInstanceOf.safeParse(val);
      const tableCheck = table ? val?.tb === table : true;
      return instanceOfCheck.success && tableCheck;
    },
    val => {
      let msgArray: string[] = [];
      const instanceOfCheck = ZRecordIdInstanceOf.safeParse(val);
      if (!instanceOfCheck.success) msgArray.push(`Must be a RecordId class`);

      const tableCheck = table ? val?.tb === table : true;
      if (!tableCheck) msgArray.push(`RecordId must be of type '${table}', not '${val?.tb}'`);

      return { message: msgArray.join("; ") };
    }
  );
}

its from the SurrealDb discord link to message by Chris Rudman

sebastianwessel commented 4 months ago

Thx @CiskaLV ! This looks good. For sure 100% better than the current invalid generated schema

sebastianwessel commented 4 months ago

Version 2.4.0 has been released, adopting this approach.