Skip to content

Commit

Permalink
Added dynamic defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
Colin McDonnell committed Oct 20, 2020
1 parent d30a9f4 commit 17f0e15
Show file tree
Hide file tree
Showing 7 changed files with 27 additions and 33 deletions.
2 changes: 0 additions & 2 deletions src/PseudoPromise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,8 @@ export class PseudoPromise<ReturnType = undefined> {
} catch (err) {
if (err instanceof ZodError) {
zerr.addIssues(err.issues);
console.log(`caught zod error in sync object!`);
return [k, INVALID] as [string, any];
}
console.log(`throwing nonzod error in sync object!`);
throw err;
}
});
Expand Down
1 change: 0 additions & 1 deletion src/__tests__/complex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ test('parse', () => {
numProm: Promise.resolve(12),
lenfun: (x: string) => x.length,
});
console.log(`SUM: ${value.sumTransformer}`);
expect(typeof value.sumTransformer).toEqual('number');
});

Expand Down
1 change: 0 additions & 1 deletion src/__tests__/pseudopromise.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ test('sync fail', async () => {
.then(async () => 15)
.then(arg => arg.toString())
.then(arg => {
console.log(arg);
return arg.length;
});

Expand Down
8 changes: 8 additions & 0 deletions src/__tests__/transformer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ test('default', () => {
expect(data).toEqual('asdf');
});

test('dynamic default', () => {
const data = z
.string()
.default(s => s._def.t)
.parse(undefined); // => "asdf"
expect(data).toEqual('string');
});

test('default when property is null or undefined', () => {
const data = z
.object({
Expand Down
13 changes: 0 additions & 13 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ export const ZodParser = (schema: z.ZodType<any>) => (
};

const def: ZodDef = schema._def as any;
console.log(`\nPARSING ${def.t}`);

let PROMISE: PseudoPromise<any> = new PseudoPromise();
(PROMISE as any)._default = true;
Expand Down Expand Up @@ -558,12 +557,10 @@ export const ZodParser = (schema: z.ZodType<any>) => (
return parsedValue;
} catch (err) {
if (err instanceof ZodError) {
console.log(`caught error at ${key}`);
const zerr: ZodError = err;
ERROR.addIssues(zerr.issues);
return INVALID;
} else {
console.log(`caught non-zod error at ${key}`);
throw err;
}
}
Expand Down Expand Up @@ -1048,7 +1045,6 @@ export const ZodParser = (schema: z.ZodType<any>) => (
// );
break;
case z.ZodTypes.transformer:
console.log(`TRANSFORMER`);
PROMISE = new PseudoPromise()
.then(() => {
try {
Expand All @@ -1062,18 +1058,10 @@ export const ZodParser = (schema: z.ZodType<any>) => (
})

.then(inputParseResult => {
console.log(`inputParseResult`);
console.log(inputParseResult);
// try {
const transformed = def.transformer(inputParseResult);
if (transformed instanceof Promise && params.async === false) {
console.log(
`transformed instanceof Promise && params.async === false`,
);

console.log(`def: ${z.inputSchema(def.output)._def.t}`);
if (z.inputSchema(def.output)._def.t !== z.ZodTypes.promise) {
console.log(`THROWING PROMISE ERROR`);
throw new Error(
"You can't call .parse on a schema containing async transformations.",
);
Expand Down Expand Up @@ -1101,7 +1089,6 @@ export const ZodParser = (schema: z.ZodType<any>) => (
})
.catch(err => {
if (!(err instanceof ZodError)) {
console.log(`NON ZOD ERROR`);
throw err;
}
ERROR.addIssues(err.issues);
Expand Down
16 changes: 6 additions & 10 deletions src/playground.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import * as z from '.';
const asyncNumberToString = z.transformer(z.number(), z.string(), async n =>
String(n),
);

const run = async () => {
console.log(
z
.object({
id: asyncNumberToString,
})
.parse({ id: 5 }),
);
const data = z
.string()
.default(schema => `${schema._def.t}`)
.parse(undefined); // => "string"
console.log(data);
};

run();
19 changes: 13 additions & 6 deletions src/types/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,16 +324,23 @@ export abstract class ZodType<
return ZodTransformer.create(this as any, this, input) as any;
}

default: <
default<
T extends Output = Output,
Opt extends ReturnType<this['optional']> = ReturnType<this['optional']>
>(
def: T,
) => ZodTransformer<Opt, this> = def => {
>(def: T): ZodTransformer<Opt, this>;
default<
T extends (arg: this) => Output,
Opt extends ReturnType<this['optional']> = ReturnType<this['optional']>
>(def: T): ZodTransformer<Opt, this>;
default(def: any) {
return ZodTransformer.create(this.optional(), this, (x: any) => {
return x === undefined ? def : x;
return x === undefined
? typeof def === 'function'
? def(this)
: def
: x;
}) as any;
};
}

// default: (val: Type) => ZodTransformer<ZodType<Type | undefined>, this> = val => {
// return ZodTransformer.create(this.optional(), this, x => {
Expand Down

0 comments on commit 17f0e15

Please sign in to comment.