Skip to content

Commit

Permalink
added rpc to collections
Browse files Browse the repository at this point in the history
  • Loading branch information
geclos committed Feb 9, 2017
1 parent cbc8fda commit b3b7824
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
33 changes: 33 additions & 0 deletions __tests__/Collection.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,5 +287,38 @@ describe('Collection', () => {
expect(collection.get(2).get('name')).toBe(newItem.name)
})
})

describe('rpc', () => {
it('sets the request', () => {
collection.rpc('foo')
expect(collection.request.label).toBe('updating')
})

describe('when it fails', () => {
beforeEach(reject)

it('sets the error', async () => {
try {
await collection.rpc('foo')
} catch (_error) {
expect(collection.error.label).toBe('updating')
expect(collection.error.body).toBe(error)
}
})
})

describe('when it succeeds', () => {
const mockResponse = [item, { id: 2, name: 'bob' }]

beforeEach(() => {
resolve(mockResponse)()
})

it('return the data', async () => {
const data = await collection.rpc('foo')
expect(data).toBe(mockResponse)
})
})
})
})
})
40 changes: 40 additions & 0 deletions src/Collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,4 +266,44 @@ export default class Collection<T: Model> {

return data
}

/**
* Call an RPC action for all those
* non-REST endpoints that you may have in
* your API.
*/
@action
async rpc (
method: string,
body?: {}
): Promise<*> {
const label: Label = 'updating' // TODO: Maybe differentiate?
const { promise, abort } = apiClient().post(
`${this.url()}/${method}`,
body || {}
)

this.request = {
label,
abort: asReference(abort),
progress: 0
}

let response

try {
response = await promise
} catch (body) {
runInAction('accept-fail', () => {
this.request = null
this.error = { label, body }
})

throw body
}

this.request = null

return response
}
}

0 comments on commit b3b7824

Please sign in to comment.