Skip to content

Commit

Permalink
feat(npm-zod): handle discriminatedUnion
Browse files Browse the repository at this point in the history
  • Loading branch information
artalar committed Jun 3, 2024
1 parent c9e6a56 commit 881f0e3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/npm-zod/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,9 @@ export const model = reatomZod(User, {
initState: JSON.parse(localStorage.getItem(KEY) || '{}'),
})
```

## Mapping

This section describes how types coverts to a specific atoms.

`union` type creates an atom with all possible state variants and `discriminatedUnion` creates an atom with all possible atoms variants.
27 changes: 26 additions & 1 deletion packages/npm-zod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
__count,
action,
Action,
throwReatomError,
} from '@reatom/core'
import { isCausedBy } from '@reatom/effects'
import {
Expand Down Expand Up @@ -251,13 +252,37 @@ export const reatomZod = <Schema extends z.ZodFirstPartySchemaTypes>(
break
}
case z.ZodFirstPartyTypeKind.ZodUnion: {
// TODO @artalar not sure about this logic
state =
def.options.find(
(type: z.ZodDefault<any>) => type._def.defaultValue?.(),
) ?? initState
break
}
case z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {
const getState = (initState: any) => {
const state = def.options.find(
(type: z.ZodDiscriminatedUnionOption<string>) => {
try {
type.parse(initState);
} catch {
return undefined;
}

return type;
},
);

throwReatomError(!state, 'Missed init state for discriminated union');

return reatomZod(state, { sync, initState, name });
};

const originAtom = atom(getState(initState), name);
theAtom = Object.assign((ctx: Ctx, value: any) => {
originAtom(ctx, getState(value));
}, originAtom);
break;
}
case z.ZodFirstPartyTypeKind.ZodOptional: {
// TODO @artalar allow `undefined` in innerType
return reatomZod(def.innerType, { sync, initState, name })
Expand Down

0 comments on commit 881f0e3

Please sign in to comment.