Skip to content

Commit

Permalink
fix: correctly serialize input array as array (#84)
Browse files Browse the repository at this point in the history
  • Loading branch information
egmacke authored Apr 17, 2024
1 parent 064ead8 commit 37becd6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/classes/polymorphic-serialiser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,18 @@ export default class PolymorphicSerializer<
): Promise<Partial<DataDocument<PrimaryType>>> {
if (Array.isArray(data)) {
const documents = await Promise.all(
data.map((d) => {
return this.serializeSingle(d, options);
Object.values(
data.reduce((acc, d) => {
// group data by type
const type = d[this.key];
if (!acc[type]) {
acc[type] = [];
}
acc[type].push(d);
return acc;
}, {} as Record<keyof PrimaryType, PrimaryType[]>)
).map((d) => {
return this.serializeType(d, options);
})
);

Expand All @@ -46,7 +56,7 @@ export default class PolymorphicSerializer<
return result;
});
} else if (data) {
return this.serializeSingle(data, options);
return this.serializeType(data, options);
}

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

private async serializeSingle(
data: PrimaryType,
options?: Partial<SerializerOptions<PrimaryType>>
private async serializeType<T extends PrimaryType>(
data: SingleOrArray<T>,
options?: Partial<SerializerOptions<T>>
) {
const serializer = this.getSerializerForData(data);
const serializer = this.getSerializerForData(Array.isArray(data) ? data[0] : data);
if (serializer) {
return serializer.serialize(data, options);
}
Expand Down
21 changes: 21 additions & 0 deletions test/issue-80.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,25 @@ describe('Issue #80 - Polymorphic serializer', () => {
expect(data.data[2].id).toEqual('3');
expect(data.data[2].type).toEqual('Model');
});

it('should serialize array as array', async () => {
const model1: Model1 = new Model1('1', 'model1');

const Model1Serializer = new Serializer<Model1>('Model1');
const Model2Serializer = new Serializer<Model2>('Model2');

const PolySerializer = new PolymorphicSerializer<Model>('Model', 'type', {
'type:Model1': Model1Serializer,
'type:Model2': Model2Serializer,
});

const data = (await PolySerializer.serialize([model1])) as {
data: Resource<Model>;
};

expect(data.data).toBeInstanceOf(Array);
expect(data.data).toHaveLength(1);
expect(data.data[0].id).toEqual('1');
expect(data.data[0].type).toEqual('Model1');
});
});

0 comments on commit 37becd6

Please sign in to comment.