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

fix(schema-utils): Return parsed key instead of the original one #22425

Merged
merged 2 commits into from May 25, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions lib/util/schema-utils.spec.ts
Expand Up @@ -51,10 +51,13 @@ describe('util/schema-utils', () => {

it('supports key schema', () => {
const s = LooseRecord(
z.string().refine((x) => x === 'bar'),
z.string()
z
.string()
.refine((x) => x === 'bar')
.transform((x) => x.toUpperCase()),
z.string().transform((x) => x.toUpperCase())
);
expect(s.parse({ foo: 'foo', bar: 'bar' })).toEqual({ bar: 'bar' });
expect(s.parse({ foo: 'foo', bar: 'bar' })).toEqual({ BAR: 'BAR' });
});

it('reports key schema errors', () => {
Expand Down
20 changes: 10 additions & 10 deletions lib/util/schema-utils.ts
Expand Up @@ -146,11 +146,11 @@ export function LooseRecord<
// Avoid error-related computations inside the loop
return z.record(z.any()).transform((input) => {
const output: Record<string, z.infer<ValueSchema>> = {};
for (const [key, val] of Object.entries(input)) {
const parsedKey = Key.safeParse(key);
const parsedValue = Value.safeParse(val);
for (const [inputKey, inputVal] of Object.entries(input)) {
const parsedKey = Key.safeParse(inputKey);
const parsedValue = Value.safeParse(inputVal);
if (parsedKey.success && parsedValue.success) {
output[key] = parsedValue.data;
output[parsedKey.data] = parsedValue.data;
}
}
return output;
Expand All @@ -161,26 +161,26 @@ export function LooseRecord<
const output: Record<string, z.infer<ValueSchema>> = {};
const issues: z.ZodIssue[] = [];

for (const [key, val] of Object.entries(input)) {
const parsedKey = Key.safeParse(key);
for (const [inputKey, inputVal] of Object.entries(input)) {
const parsedKey = Key.safeParse(inputKey);
if (!parsedKey.success) {
for (const issue of parsedKey.error.issues) {
issue.path.unshift(key);
issue.path.unshift(inputKey);
issues.push(issue);
}
continue;
}

const parsedValue = Value.safeParse(val);
const parsedValue = Value.safeParse(inputVal);
if (!parsedValue.success) {
for (const issue of parsedValue.error.issues) {
issue.path.unshift(key);
issue.path.unshift(inputKey);
issues.push(issue);
}
continue;
}

output[key] = parsedValue.data;
output[parsedKey.data] = parsedValue.data;
continue;
}

Expand Down