Skip to content

Commit ab35ee8

Browse files
committed
feat: serialize polymorphic documents
1 parent 769e3cf commit ab35ee8

File tree

2 files changed

+73
-2
lines changed

2 files changed

+73
-2
lines changed

src/classes/polymorphic-serialiser.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,21 @@ export default class PolymorphicSerializer<
2929
options?: Partial<SerializerOptions<PrimaryType>>
3030
): Promise<Partial<DataDocument<PrimaryType>>> {
3131
if (Array.isArray(data)) {
32-
data.map((d) => {
33-
return this.serializeSingle(d, options);
32+
const documents = await Promise.all(
33+
data.map((d) => {
34+
return this.serializeSingle(d, options);
35+
})
36+
);
37+
38+
return documents.reduce((result, document) => {
39+
if (!result) {
40+
return document;
41+
}
42+
43+
result.data = [result.data ?? [], document.data ?? []].flat();
44+
result.included = [result.included ?? [], document.included ?? []].flat();
45+
46+
return result;
3447
});
3548
} else if (data) {
3649
return this.serializeSingle(data, options);

test/issue-80.test.ts

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { PolymorphicSerializer, Serializer } from '../lib';
2+
import Resource from '../lib/models/resource.model';
3+
4+
describe('Issue #80 - Polymorphic serializer', () => {
5+
abstract class Model {
6+
public type: string;
7+
8+
constructor(public id: string) {}
9+
}
10+
11+
class Model1 extends Model {
12+
constructor(id: string, public model1: string) {
13+
super(id);
14+
this.type = 'type:Model1';
15+
}
16+
}
17+
18+
class Model2 extends Model {
19+
constructor(id: string, public model2: string) {
20+
super(id);
21+
this.type = 'type:Model2';
22+
}
23+
}
24+
25+
class Model3 extends Model {
26+
constructor(id: string, public model2: string) {
27+
super(id);
28+
this.type = 'type:Model3';
29+
}
30+
}
31+
32+
it('should work polymorphicly', async () => {
33+
const model1: Model1 = new Model1('1', 'model1');
34+
const model2: Model2 = new Model2('2', 'model2');
35+
const model3: Model3 = new Model3('3', 'model3');
36+
37+
const Model1Serializer = new Serializer<Model1>('Model1');
38+
const Model2Serializer = new Serializer<Model2>('Model2');
39+
40+
const PolySerializer = new PolymorphicSerializer<Model>('Model', 'type', {
41+
'type:Model1': Model1Serializer,
42+
'type:Model2': Model2Serializer,
43+
});
44+
45+
const data = (await PolySerializer.serialize([model1, model2, model3])) as {
46+
data: Resource<Model>;
47+
};
48+
49+
expect(data.data).toBeInstanceOf(Array);
50+
expect(data.data).toHaveLength(3);
51+
expect(data.data[0].id).toEqual('1');
52+
expect(data.data[0].type).toEqual('Model1');
53+
expect(data.data[1].id).toEqual('2');
54+
expect(data.data[1].type).toEqual('Model2');
55+
expect(data.data[2].id).toEqual('3');
56+
expect(data.data[2].type).toEqual('Model');
57+
});
58+
});

0 commit comments

Comments
 (0)