Skip to content

Commit

Permalink
Merge pull request #239 from digitalsadhu/reflexive-relationship
Browse files Browse the repository at this point in the history
Reflexive relationship
  • Loading branch information
BenjaminHorn authored Jul 13, 2017
2 parents 882c039 + 067283c commit 42ede51
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ function parseRelations (data, relations, options) {

var relationship = null

if (!_.isUndefined(fk)) {
if (!_.isUndefined(fk) && relation.modelTo !== relation.modelFrom) {
if (_.isArray(fk)) {
relationship = makeRelations(toType, fk, options)
} else {
Expand Down
61 changes: 61 additions & 0 deletions test/reflexiveRelationship.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/* global describe, beforeEach, it */

var request = require('supertest')
var loopback = require('loopback')
var expect = require('chai').expect
var JSONAPIComponent = require('../')

var app, Folder

describe('reflexive relationship', function () {
beforeEach(function (done) {
app = loopback()
app.set('legacyExplorer', false)
var ds = loopback.createDataSource('memory')
// create models
Folder = ds.createModel('folder', {
id: { type: Number, id: true },
name: String
})

Folder.hasMany(Folder, { as: 'children', foreignKey: 'parentId' })
Folder.belongsTo(Folder, { as: 'parent', foreignKey: 'parentId' })
// add models
app.model(Folder)

// make data
Folder.create(
[
{ name: 'Folder 1', parentId: 0 },
{ name: 'Folder 2', parentId: 1 },
{ name: 'Folder 3', parentId: 1 },
{ name: 'Folder 4', parentId: 3 }
],
function (err, foders) {
if (err) console.error(err)
done()
}
)

app.use(loopback.rest())
JSONAPIComponent(app, { restApiRoot: '' })
})

it('should make initial data', function (done) {
request(app).get('/folders').end(function (err, res) {
expect(err).to.equal(null)
expect(res.body.data.length).to.equal(4)
done(err)
})
})

it('should have children', function (done) {
request(app).get('/folders/1/children').end(function (err, res) {
expect(err).to.equal(null)
expect(res.body.data.length).to.equal(2)
expect(res.body.data[0].relationships.children.data).to.equal(undefined)
expect(res.body.data[1].relationships.children.data).to.equal(undefined)
done(err)
})
})
})

0 comments on commit 42ede51

Please sign in to comment.