Skip to content

Commit

Permalink
allow a tranform function to return primitive types
Browse files Browse the repository at this point in the history
  • Loading branch information
Ralph Huwiler committed Mar 17, 2018
1 parent 04b65ed commit a173997
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Bumblebee/Scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,18 @@ class Scope {
}

async _item (data, transformer) {
// if there is no data to be transformed, return null
if (!data) return null

// get a transformer instance and tranform data
let transformerInstance = this._getTransformerInstance(transformer)

let transformed = await transformerInstance.transform(await data, this._ctx)

let includeData = await transformerInstance.processIncludedResources(this, await data)
// if a primitive type is returned, we can not add included data.
if (!(transformed instanceof Object)) return transformed

// get included data and append it to the object
let includeData = await transformerInstance.processIncludedResources(this, await data)
return Object.assign(includeData, transformed)
}

Expand Down
17 changes: 17 additions & 0 deletions test/transformer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ class IDTransformer extends TransformerAbstract {
}
}

class PrimitiveTransformer extends TransformerAbstract {
transform (model) {
return model.name
}
}

test.group('Transformer', () => {
test('a transformer maps item properties', async (assert) => {
let data = {item_id: 3}
Expand All @@ -45,6 +51,17 @@ test.group('Transformer', () => {
assert.deepEqual(transformed, [{id: 3}, {id: 55}])
})

test('a transformer can return an array', async (assert) => {
let data = [{name: 'John'}, {name: 'Bob'}]

let transformed = await Bumblebee.create()
.collection(data)
.transformWith(PrimitiveTransformer)
.toArray()

assert.deepEqual(transformed, ['John', 'Bob'])
})

test('a transformer can transform a collection of lucid rows', async (assert) => {
let data = {rows: [{item_id: 3}, {item_id: 55}]}

Expand Down

0 comments on commit a173997

Please sign in to comment.