Skip to content

Commit a0a7630

Browse files
committed
fix polymorphic belongsTo with include
modelTo should not be expected
1 parent ed84ddf commit a0a7630

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

lib/serializer.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function defaultSerialize (options, cb) {
2727
*/
2828
if (options.requestedIncludes) {
2929
try {
30-
handleIncludes(resultData, options.requestedIncludes, options.relationships);
30+
handleIncludes(resultData, options.requestedIncludes, options.relationships, options.app);
3131
} catch (err) {
3232
cb(err);
3333
}
@@ -313,7 +313,7 @@ function makeLinks (links, item) {
313313
* @throws {Error}
314314
* @return {undefined}
315315
*/
316-
function handleIncludes (resp, includes, relations) {
316+
function handleIncludes (resp, includes, relations, app) {
317317
var resources = _.isArray(resp.data) ? resp.data : [resp.data];
318318

319319
if (typeof includes === 'string') {
@@ -328,7 +328,13 @@ function handleIncludes (resp, includes, relations) {
328328
return includes.map(function (include) {
329329
var relation = relations[include];
330330
var propertyKey = relation.keyFrom;
331-
var plural = utils.pluralForModel(relation.modelTo);
331+
var plural = '';
332+
if (relation.polymorphic) {
333+
var discriminator = resource.attributes[relation.polymorphic.discriminator];
334+
plural = utils.pluralForModel(app.models[discriminator]);
335+
} else {
336+
plural = utils.pluralForModel(relation.modelTo);
337+
}
332338
var embeds = [];
333339

334340
// If relation is belongsTo then pk and fk are the other way around

test/belongsToPolymorphic.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,17 @@ describe('loopback json api belongsTo polymorphic relationships', function () {
6363
done();
6464
});
6565
});
66+
67+
it('should return the Post that this file belongs to when included flag is present', function (done) {
68+
request(app).get('/files/1?include=parent')
69+
.end(function (err, res) {
70+
expect(err).to.equal(null);
71+
expect(res.body.errors).to.equal(undefined);
72+
expect(res.body.included).to.be.an('array');
73+
expect(res.body.included[0].type).to.equal('posts');
74+
expect(res.body.included[0].id).to.equal('1');
75+
done();
76+
});
77+
});
6678
});
6779
});

0 commit comments

Comments
 (0)