Skip to content

Commit

Permalink
Make it so anywhere a Value or InputValue is expected, it can be arbi…
Browse files Browse the repository at this point in the history
…trary nested Array or Object.

Required manually defining a few types to get around a zod recursion issue, but they're simple types.

Part of #42.
  • Loading branch information
jkomoros committed Jul 8, 2023
1 parent 56578ac commit 8ad35e6
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,24 @@ const nonTypeRegExp = new RegExp('(?!type$)');

const nonTypeKey = z.string().regex(absoluteRegExp(new RegExp(nonTypeRegExp.source + genericIDExtraRegExp.source)));

const valueObject = z.record(nonTypeKey, leafValue);
//We have to define these types manually because of the use of recursion and z.lazy(). Luckily they're easy to define.
export type ValueObject = {
[key : string]: Value
};

export type ValueObject = z.infer<typeof valueObject>;
export type ValueArray = Value[];

const valueArray = z.array(leafValue);
const valueObject : z.ZodType<ValueObject> = z.record(nonTypeKey, z.lazy(() => value));

export type ValueArray = z.infer<typeof valueArray>;
const valueArray : z.ZodType<ValueArray> = z.array(z.lazy(() => value));

const value = z.union([
leafValue,
valueObject,
valueArray
]);

export type Value = z.infer<typeof value>;
export type Value = LeafValue | ValueObject | ValueArray;

const inputLeafValue = z.union([
z.null(),
Expand All @@ -78,16 +81,27 @@ const inputLeafValue = z.union([
z.boolean(),
]);

const inputValueObject = z.record(nonTypeKey, inputLeafValue);
//We have to define these types manually because of the use of recursion and z.lazy(). Luckily they're easy to define.
type InputLeafValue = z.infer<typeof inputLeafValue>;

type InputValueObject = {
[key : string] : InputValue
};

type InputValueArray = InputValue[];

const inputValueObject : z.ZodType<InputValue>= z.record(nonTypeKey, z.lazy(() => inputValue));

const inputValueArray = z.array(inputLeafValue);
const inputValueArray : z.ZodType<InputValueArray> = z.array(z.lazy(() => inputValue));

export const inputValue = z.union([
inputLeafValue,
inputValueObject,
inputValueArray
]);

type InputValue = InputLeafValue | InputValueObject | InputValueArray;

//In the vast majority of cases, we don't really want a value but a non-object
//value. Schema checking gets confused with sub-seeds otherwise; any sub-object
//might just be a ValueObject, so it stops helping fill in sub-seed properties.
Expand Down

0 comments on commit 8ad35e6

Please sign in to comment.