Last active
November 11, 2025 19:07
-
-
Save severi/5d181a3e779f41a5e5fce1b7dcd17a89 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { z } from 'zod'; | |
| const VehicleSchema = z.object({ | |
| id: z.string(), | |
| itemType: z.literal('VEHICLE'), | |
| licencePlateNumber: z.string(), | |
| }); | |
| const HouseSchema = z.object({ | |
| id: z.string(), | |
| itemType: z.literal('HOUSE'), | |
| address: z.string(), | |
| city: z.string(), | |
| country: z.string(), | |
| }); | |
| const ItemModelZod = z.discriminatedUnion('itemType', [VehicleSchema, HouseSchema]); | |
| const ItemEntity = new Entity({ | |
| model: { | |
| entity: 'item', | |
| service: 'auth', | |
| version: '01', | |
| }, | |
| attributes: { | |
| id: { | |
| type: 'string', | |
| }, | |
| itemType: { | |
| type: 'string' | |
| }, | |
| /* | |
| also allow any other attributes to be inserted besides these two i.e. in this case | |
| - licencePlateNumber | |
| - address | |
| - city | |
| - country | |
| without having to explicitly define them here | |
| With for example large/complex discriminated unions keeping this up-to-date could be quite cumbersome | |
| and force us to basically list all the possible attributes that an item in the union might have | |
| One interesting option could of course be if these could be automatically created from the zod schema... | |
| */ | |
| }, | |
| indexes: { | |
| byItemType: { | |
| pk: { | |
| field: 'pk', | |
| composite: ['itemType'] | |
| }, | |
| sk: { | |
| field: 'sk', | |
| composite: ['id'] | |
| } | |
| } | |
| } | |
| }, { table, client }); | |
| const item = ItemModelZod.parse({ | |
| id: '123456', | |
| itemType: 'VEHICLE', | |
| licencePlateNumber: 'abcde', | |
| }); | |
| await ItemEntity.put(item).go(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In it case helps anyone, here is link to discussion with type inference / assertion solution that has been working quite well tywalch/electrodb#216 (comment)