Skip to content

Commit

Permalink
feat: Inject cozy-client - stage 11 - cozyFetchJSON
Browse files Browse the repository at this point in the history
simple wrapper around internal `fetchJSON()` maintaining compatibility with the old cozy-client-js
  • Loading branch information
edas committed Feb 20, 2019
1 parent 4ebc20a commit 672f41f
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/lib/stack-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ const updateAccessToken = function(token) {
*
* @function
* @private
* @returns {Promise} the full raw JSON playload
* @returns {Promise} the full raw JSON payload
*/
const fetchJSON = function(method, path, body, options={}) {

Expand Down Expand Up @@ -302,6 +302,29 @@ const getContext = function() {
return fetchJSON('GET', '/settings/context')
}

/**
* Fetch a resource on the cozy stack
* with a prototype compatible with the legacy cozy-client-js
*
* @function
* @param {object} cozy - cozy-client-js
* @param {string} method - HTTP method
* @param {string} path
* @param {object} body
* @returns {Promise}
*/
const cozyFetchJSON = function(cozy, method, path, body) {
return fetchJSON(method, path, body).then(
json => {
const responseData = Object.assign({}, json.data)
if (responseData.id) {
responseData._id = responseData.id
}
return responseData
}
)
}

/**
* Initializes the functions to call the cozy stack
*
Expand Down Expand Up @@ -333,7 +356,8 @@ export default {
iconProps: getAppIconProps,
cozyURL: getCozyURLOrigin
},
updateAccessToken,
updateAccessToken,
cozyFetchJSON,
logout,
init 
}
49 changes: 49 additions & 0 deletions test/lib/stack-client/stack-client.cozyfetchjson.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import stack from 'lib/stack-client'

describe("stack client", () => {

describe("cozyFetchJSON", () => {

let json = jest.fn().mockReturnValue({
data: { id: "myid" }
})
let fetch = jest.fn().mockResolvedValue({
status:200,
headers: {
get: (header) => 'application/json'
},
json
})
let cozyClient = {
getStackClient: () => {
return {
token: { token: "mytoken"},
uri: "https://test.mycozy.cloud",
fetch
}
}
}
let params = {
cozyClient,
onCreateApp: function() {},
onDeleteApp: function() {},
}

beforeAll(async () => {
await stack.init(params)
})

it("should transform `id` in `_id`", async () => {
const data = await stack.cozyFetchJSON('_', 'GET', '/path')
expect( data._id ).toBe('myid')
})

it("should call fetch from cozy-client", async () => {
fetch.mockClear()
const data = await stack.cozyFetchJSON('_', 'GET', '/path')
expect( fetch ).toHaveBeenCalled()
})

})

})

0 comments on commit 672f41f

Please sign in to comment.