sebastianwessel / surrealdb-client-generator

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

Improve record handling #25

Closed sebastianwessel closed 2 months ago

sebastianwessel commented 2 months ago

Improve handling of record links

CiskaLV commented 2 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 2 months ago

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

sebastianwessel commented 2 months ago

Version 2.4.0 has been released, adopting this approach.