Skip to content
Open
Show file tree
Hide file tree
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
8 changes: 4 additions & 4 deletions packages/zod/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import type {
TypeDefFieldIsArray,
TypeDefFieldIsOptional,
} from '@zenstackhq/schema';
import type Decimal from 'decimal.js';
import type z from 'zod';
import type { decimalSchema, bytesSchema } from './utils';

/**
* Scalar-only shape returned by the no-options `makeModelSchema` overload.
Expand Down Expand Up @@ -106,10 +106,10 @@ type FieldTypeZodMap = {
Int: z.ZodNumber;
BigInt: z.ZodBigInt;
Float: z.ZodNumber;
Decimal: z.ZodType<Decimal>;
Decimal: typeof decimalSchema;
Boolean: z.ZodBoolean;
DateTime: z.ZodType<Date>;
Bytes: z.ZodType<Uint8Array>;
DateTime: z.ZodDate;
Bytes: typeof bytesSchema;
Json: JsonZodType;
};

Expand Down
3 changes: 3 additions & 0 deletions packages/zod/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import Decimal from 'decimal.js';
import { z } from 'zod';
import { SchemaFactoryError } from './error';

export const decimalSchema = z.custom<Decimal>((val) => Decimal.isDecimal(val));
export const bytesSchema = z.instanceof(Uint8Array) as z.ZodCustom<Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>>;

function getArgValue<T extends string | number | boolean>(expr: Expression | undefined): T | undefined {
if (!expr || !ExpressionUtils.isLiteral(expr)) {
return undefined;
Expand Down
8 changes: 8 additions & 0 deletions packages/zod/test/factory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ describe('SchemaFactory - makeModelSchema', () => {
expect(userSchema.safeParse({ ...validUser, metadata: { key: BigInt(1) } }).success).toBe(false);
expect(userSchema.safeParse({ ...validUser, metadata: [BigInt(1)] }).success).toBe(false);
});

it('infers correct input types for fields', () => {
const _userSchema = factory.makeModelSchema('User');
type UserInput = z.input<typeof _userSchema>;
expectTypeOf<UserInput['birthdate']>().toEqualTypeOf<Date | null | undefined>();
expectTypeOf<UserInput['balance']>().toEqualTypeOf<Decimal>();
expectTypeOf<UserInput['avatar']>().toEqualTypeOf<Uint8Array | null | undefined>();
});
});

describe('string validation attributes', () => {
Expand Down
Loading