Last active
September 27, 2018 23:48
-
-
Save jimmielemontgomery/2328d2af8a096731d000d1e5ec7a384d to your computer and use it in GitHub Desktop.
api-stub-response-example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
a simple generalized example of stubbing an API response to save the effort of standing up or proxying APIs | |
for repeatable UI work prior to wiring up or staging | |
simply handle the success or fail response object, in this example it's just success | |
an object's data attribute has the desired API response body like: {data: API-response-JSON-here} | |
this specific case was derived from the jobs redux global handling and could easily be repurposed for any approach | |
note prexisting responses can be found via integration/staging/etc just | |
pretty-print app.js or whatever in dev tools, search and set breakpoints for fetch handling | |
*/ | |
/** | |
* Async Actions | |
*/ | |
export const fetchSomethings = (page=0, type) => (dispatch, getState) => { | |
const orgId = getOrgId( getState() ); | |
return new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
var delay = 456 | |
,url = `/org/${orgId}/things/` | |
,params = {params: {...defaultParams, page: page}} | |
; | |
console.warn(`fake:http.fetch(${url}...params in ${delay}ms)`, params); | |
resolve({ | |
"data": [ | |
{ | |
"id": 9876543210, | |
"name": "example of API response...with whatever is desired" | |
} | |
], | |
"status": 200, | |
"statusText": "fake okay", | |
"headers": { | |
"date": (new Date).toGMTString(), | |
"server": "nginx/1.23.45", | |
"strict-transport-security": "max-age=15724800; includeSubDomains", | |
"content-type": "application/json", | |
"status": "200", | |
"//content-length": "228//bytes of compressed body" | |
}, | |
"config": { | |
"transformRequest": {}, | |
"transformResponse": {}, | |
"timeout": 10000, | |
"xsrfCookieName": "XSRF-TOKEN", | |
"xsrfHeaderName": "X-XSRF-TOKEN", | |
"maxContentLength": -1, | |
"headers": { | |
"Accept": "application/json", | |
"X-Auth-Token": "not!", | |
"X-Organization-Id": "1" | |
}, | |
"baseURL": "/things", | |
"method": "get", | |
"url": "/things/v1/org/1/active/?page=0&pageSize=20" | |
}, | |
"request": {} | |
}); | |
}, delay); | |
}) | |
// ALL OF THE FOLLOWING AS-ORIGINAL except TODO comment disabling the return fetch | |
// TODO UNCOMMENT! return someThing.get(`/org/${orgId}/things/`, {params: {...defaultParams, page: page}}) | |
.then((resp) => { | |
const resetIoJobs = (page === 0); | |
dispatch(receiveSomething(resp.data, stuff)); | |
return resp; | |
}, (resp) => { | |
dispatch(receiveSomething(resp.data, stuff)); | |
return resp; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment