Skip to content
Merged
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
20 changes: 20 additions & 0 deletions packages/schema/src/tests/utils/idl.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,24 @@ describe('idl', () => {
});
});
});

describe('object with enum field with default', () => {
const Schema = z.object({
visibility: z
.enum(['public', 'friends_and_followers', 'friends_only'])
.default('friends_only')
});

it('converts enum with default to IDL', () => {
expect(schemaToIdl({schema: Schema, value: {visibility: 'friends_and_followers'}})).toEqual({
visibility: {friends_and_followers: null}
});
});

it('converts enum with default from IDL', () => {
expect(
schemaFromIdl({schema: Schema, value: {visibility: {friends_and_followers: null}}})
).toEqual({visibility: 'friends_and_followers'});
});
});
});
21 changes: 21 additions & 0 deletions packages/schema/src/utils/idl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ export const schemaToIdl = ({schema, value}: IdlParams): unknown => {
);
}

if (schema instanceof z.ZodDefault) {
return schemaToIdl({schema: schema._zod.def.innerType, value});
}

if (schema instanceof z.ZodEnum) {
return {[value as string]: null};
}

return value;
};

Expand Down Expand Up @@ -147,5 +155,18 @@ export const schemaFromIdl = ({schema, value}: IdlParams): unknown => {
);
}

if (schema instanceof z.ZodDefault) {
return schemaFromIdl({schema: schema._zod.def.innerType, value});
}

if (schema instanceof z.ZodEnum) {
const obj = value as Record<string, unknown>;
const keys = Object.keys(obj);
if (keys.length === 1) {
return keys[0];
}
return value;
}

return value;
};
Loading