Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(schema-utils): Return parsed key instead of the original one (#22425
)

Co-authored-by: Michael Kriese <michael.kriese@visualon.de>
  • Loading branch information
zharinov and viceice committed May 25, 2023
1 parent 290b78d commit 2fba61a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
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

0 comments on commit 2fba61a

Please sign in to comment.