Skip to content

Commit 37becd6

Browse files
authored
fix: correctly serialize input array as array (#84)
1 parent 064ead8 commit 37becd6

File tree

2 files changed

+38
-7
lines changed

2 files changed

+38
-7
lines changed

Diff for: src/classes/polymorphic-serialiser.ts

+17-7
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,18 @@ export default class PolymorphicSerializer<
3030
): Promise<Partial<DataDocument<PrimaryType>>> {
3131
if (Array.isArray(data)) {
3232
const documents = await Promise.all(
33-
data.map((d) => {
34-
return this.serializeSingle(d, options);
33+
Object.values(
34+
data.reduce((acc, d) => {
35+
// group data by type
36+
const type = d[this.key];
37+
if (!acc[type]) {
38+
acc[type] = [];
39+
}
40+
acc[type].push(d);
41+
return acc;
42+
}, {} as Record<keyof PrimaryType, PrimaryType[]>)
43+
).map((d) => {
44+
return this.serializeType(d, options);
3545
})
3646
);
3747

@@ -46,7 +56,7 @@ export default class PolymorphicSerializer<
4656
return result;
4757
});
4858
} else if (data) {
49-
return this.serializeSingle(data, options);
59+
return this.serializeType(data, options);
5060
}
5161

5262
return Object.values(this.serialisers)[0].serialize(data, options);
@@ -76,11 +86,11 @@ export default class PolymorphicSerializer<
7686
return super.createResource(data, options, helpers, relatorDataCache);
7787
}
7888

79-
private async serializeSingle(
80-
data: PrimaryType,
81-
options?: Partial<SerializerOptions<PrimaryType>>
89+
private async serializeType<T extends PrimaryType>(
90+
data: SingleOrArray<T>,
91+
options?: Partial<SerializerOptions<T>>
8292
) {
83-
const serializer = this.getSerializerForData(data);
93+
const serializer = this.getSerializerForData(Array.isArray(data) ? data[0] : data);
8494
if (serializer) {
8595
return serializer.serialize(data, options);
8696
}

Diff for: test/issue-80.test.ts

+21
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,25 @@ describe('Issue #80 - Polymorphic serializer', () => {
5555
expect(data.data[2].id).toEqual('3');
5656
expect(data.data[2].type).toEqual('Model');
5757
});
58+
59+
it('should serialize array as array', async () => {
60+
const model1: Model1 = new Model1('1', 'model1');
61+
62+
const Model1Serializer = new Serializer<Model1>('Model1');
63+
const Model2Serializer = new Serializer<Model2>('Model2');
64+
65+
const PolySerializer = new PolymorphicSerializer<Model>('Model', 'type', {
66+
'type:Model1': Model1Serializer,
67+
'type:Model2': Model2Serializer,
68+
});
69+
70+
const data = (await PolySerializer.serialize([model1])) as {
71+
data: Resource<Model>;
72+
};
73+
74+
expect(data.data).toBeInstanceOf(Array);
75+
expect(data.data).toHaveLength(1);
76+
expect(data.data[0].id).toEqual('1');
77+
expect(data.data[0].type).toEqual('Model1');
78+
});
5879
});

0 commit comments

Comments
 (0)