Skip to content

Commit 6e6995b

Browse files
fix: nested entity references (#1)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
1 parent 7c814e3 commit 6e6995b

File tree

2 files changed

+145
-66
lines changed

2 files changed

+145
-66
lines changed

src/__tests__/entityReference.spec.ts

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const v1_schema = z.object({
1313
z.object({
1414
name: z.string(),
1515
value: z.string(),
16-
}),
16+
})
1717
),
1818
});
1919

@@ -33,7 +33,7 @@ const v2_schema = z.object({
3333
value: z.string(),
3434
masked: z.literal(false),
3535
}),
36-
]),
36+
])
3737
),
3838
});
3939

@@ -192,3 +192,89 @@ describe("entityReference", () => {
192192
});
193193
});
194194
});
195+
196+
const migrate_child_v1 = z.object({ v: z.literal(1), a: z.number() });
197+
const migrate_child_v2 = z.object({ v: z.literal(2), b: z.number() });
198+
const migrateChildVersioned = createVersionedEntity({
199+
latestVersion: 2,
200+
getVersion(data) {
201+
if (typeof data !== "object" || data === null) {
202+
return null;
203+
}
204+
// @ts-expect-error
205+
return data["v"];
206+
},
207+
versionMap: {
208+
1: defineVersion({
209+
initial: true,
210+
schema: migrate_child_v1,
211+
}),
212+
2: defineVersion({
213+
initial: false,
214+
schema: migrate_child_v2,
215+
up(
216+
old: z.infer<typeof migrate_child_v1>
217+
): z.infer<typeof migrate_child_v2> {
218+
return { v: 2, b: old.a };
219+
},
220+
}),
221+
},
222+
});
223+
const migrateChildSchema = entityReference(migrateChildVersioned);
224+
225+
const migrate_parent_v1 = z.object({
226+
v: z.literal(1),
227+
c: z.number(),
228+
child: migrateChildSchema,
229+
});
230+
const migrate_parent_v2 = z.object({
231+
v: z.literal(2),
232+
d: z.number(),
233+
child: migrateChildSchema,
234+
});
235+
236+
const migrateParentVersioned = createVersionedEntity({
237+
latestVersion: 2,
238+
getVersion(data) {
239+
if (typeof data !== "object" || data === null) {
240+
return null;
241+
}
242+
// @ts-expect-error
243+
return data["v"];
244+
},
245+
versionMap: {
246+
1: defineVersion({
247+
initial: true,
248+
schema: migrate_parent_v1,
249+
}),
250+
2: defineVersion({
251+
initial: false,
252+
schema: migrate_parent_v2,
253+
up(
254+
old: z.infer<typeof migrate_parent_v1>
255+
): z.infer<typeof migrate_parent_v2> {
256+
return { v: 2, d: old.c, child: old.child };
257+
},
258+
}),
259+
},
260+
});
261+
const migrateParentSchema = entityReference(migrateParentVersioned);
262+
263+
describe("nested entityReference", () => {
264+
it("nest migrations should migrate to latest version", () => {
265+
const result = migrateParentSchema.safeParse({
266+
v: 1,
267+
c: 4,
268+
child: {
269+
v: 1,
270+
a: 8,
271+
},
272+
});
273+
274+
expect(result.success).toBe(true);
275+
276+
if (result.success) {
277+
expect(result.data).toEqual({ v: 2, d: 4, child: { v: 2, b: 8 } });
278+
}
279+
});
280+
});

0 commit comments

Comments
 (0)