return (dispatch) => { fetch(`${baseURL}/api/user`, { credentials: 'include', }) .then((res) => { if (res.status === 401) { throw new Error('Invalid username or password'); } else if (res.status >= 400) { throw new Error(`Bad response from server ${res.status} ${res.statusText}`); } return res.json(); }) .then((res) => { if (res.error) { throw new Error(res.error.message); } dispatch(setUser(res)); }) .catch((err) => { console.log(err); dispatch(clearUser()); }); };
return (dispatch, state) => { // console.log('about to run dispatch(dataFetchPhotosRequest()); in static/actions/photo.js'); dispatch(dataFetchPhotosRequest()); return fetch(`${SERVER_URL}/api/v1/getalbums/${albumId}/`, { credentials: 'include', headers: { Accept: 'application/json', Authorization: `JWT ${token}` }, }) .then(checkHttpStatus) .then(parseJSON) .then(response => { // console.log("response within static/actions/photo.js"); dispatch(dataReceivePhotos(response)); }) .catch(error => { if (error.response.status === 401) { dispatch(authLoginUserFailure(error)); dispatch(push('/login')); } }); };
return new Promise((resolve, reject) => { fetch(`${APIConstants.SERVER_NAME}${APIConstants.JOIN_GAME}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'cache-control': 'no-cache' }, body: JSON.stringify({ 'Id': 0, 'RoundStartTime': roundStartTime, 'RoundEndTime': null, 'Gambler': null, 'GamblerId': gamblerId, 'KenoGameId': gameId, 'KenoGame': null }) }).then( (responseGame) => responseGame.json()) .then((jsonGame) => { resolve(jsonGame) }).catch((ex) => { ErrorHandler(ex) }) })
return new Promise((resolve, reject) => { fetch(_parseUrl(url), _parseOptions(options)).then( async (response) => { if (response.status >= 400) { try { reject({ _error: await response.json() }) } catch (err) { reject({ _error: response.statusText }) } } else { try { resolve(await response.json()) } catch (err) { resolve(response.statusText) } } }, async (response) => { reject({ _error: await response.json() }) } ) })
(dispatch) => { const data = JSON.stringify({ username, password }); const url = `${app}/api/login`; fetch(url, { method: 'POST', credentials: 'same-origin', body: data, headers: { 'Content-Type': 'application/json', }, }) .then((res) => res.json()) .then((response) => { dispatch(optimisticSignIn(response)); const locationAllowed = confirm('Enable Location Services?'); getCoordsAndZip(dispatch, locationAllowed); browserHistory.push('/'); }) .catch((err) => { if (err) { console.log(err); } }); }
navigator.geolocation.getCurrentPosition(position => { let lat = position.coords.latitude; let lng = position.coords.longitude; dispatch({ type: 'GET_USER_COORDS', lat, lng, }); let zipURL = `http://zipcodehelper.herokuapp.com/api/zip?lng=${lng}&lat=${lat}`; fetch(zipURL, { method: 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', }, }) .then((res) => res.json()) .then(res => { dispatch({ type: 'GET_USER_ZIP', zip: res, }); }); }, error => {
return (dispatch) => { dispatch(setPropertyUser('registering', true)); return fetch(`${baseURL}/api/register`, { credentials: 'include', method: 'post', body: JSON.stringify({ name: userData.name, email: userData.email, password: userData.password, }), headers: new Headers({ 'Content-Type': 'application/json', }), }) .then((res) => { if (res.status >= 400) { throw new Error(`Bad response from server ${res.status} ${res.statusText}`); } return res.json(); }) .then((res) => { if (res.error) { throw new Error(res.error.message); } dispatch(setUser(res)); refreshSocket(); cb(res); }) .catch((err) => { console.log(err); dispatch(setPropertyUser('registering', false)); dispatch(setUserErrors({ base: [err.message] })); }); };
var callAPI = function(url, data, method="POST") { const { csrf } = data; delete data.csrf; let fetchObj = { method: method, credentials: 'same-origin', headers: { 'Accept': "application/json", 'Content-Type': "application/json", 'X-CSRF-TOKEN': csrf } }; fetchObj = Object.assign({}, fetchObj, Object.keys(data).length>0?{body:JSON.stringify(data)}:{}); return fetch(url, fetchObj) .then(response => { if (response.status >= 200 && response.status < 300) return response; else throw new Error(response.statusText); }) .then(response => response.json().then(json => Object.assign({}, json, {csrf:response.headers.get('X-CSRF-TOKEN')}))); };
/** * Sends HTTP request to the specified API endpoint. This method is just * a convenient wrapper around isomorphic fetch(..): * * - If API service has auth token, Authorization header is automatically * added to the request; * * - If no Content-Type header set in options, it is automatically set to * "application/json". In case you want to avoid it, pass null into * Content-Type header option. * * For additional details see https://github.github.io/fetch/ * @param {String} enpoint Should start with slash, like /endpoint. * @param {Object} options Optional. Fetch options. * @return {Promise} It resolves to the HTTP response object. To get the * actual data you probably want to call .json() method of that object. * Mind that this promise rejects only on network errors. In case of * HTTP errors (404, etc.) the promise will be resolved successfully, * and you should check .status or .ok fields of the response object * to find out the response status. */ async fetch(endpoint, options = {}) { const { base, token, } = this.private; const headers = options.headers ? _.clone(options.headers) : {}; if (token) headers.Authorization = `Bearer ${token}`; switch (headers['Content-Type']) { case null: delete headers['Content-Type']; break; case undefined: headers['Content-Type'] = 'application/json'; break; default: } /* Throttling of API calls should not happen at server in production. */ if (API_THROTTLING && (isomorphy.isClientSide() || isomorphy.isDevBuild())) { const now = Date.now(); lastApiCallTimestamp += MIN_API_CALL_DELAY; if (lastApiCallTimestamp > now) { await delay(lastApiCallTimestamp - now); } else lastApiCallTimestamp = now; } return fetch(`${base}${endpoint}`, { ...options, headers, }) .catch((e) => { setErrorIcon(ERROR_ICON_TYPES.NETWORK, `${base}${endpoint}`, e.message); throw e; }); }
return (dispatch) => { return fetch(`${baseURL}/api/addresses/${id}`, { credentials: 'include', method: 'delete', }) .then((res) => { if (res.status >= 400) { throw new Error(`Bad response from server ${res.status} ${res.statusText}`); } return res.json(); }) .then((res) => { if (res.error) { throw new Error(res.error.message); } dispatch(removeAddressFromAddresses(res)); cb(res); }) .catch((err) => { console.log(err); }); };
return dispatch => { dispatch(requestPosts(subreddit)); return fetch(`http://www.reddit.com/r/${subreddit}.json`) .then(response => response.json()) .then(json => dispatch(receivePosts(subreddit, json))) }
componentDidMount() { fetch('/api/mywordlist') .then(function(res){return res.json()}) .then(this.setWordList.bind(this)) .then(this.setTest.bind(this)) }
export function fetchData(query) { return fetch(`https://fcctop100.herokuapp.com/api/fccusers/top/${query}`) .then(response => response.json()); }
return dispatch => { dispatch( requestFiles() ); return fetch( 'http://localhost:7171/' ) .then( response => response.json() ) .then( json => dispatch( receiveFiles( json ) ) ); };
export function searchPlaces(latitude, longitude, radius) { let uri = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=${radius}&types=park|zoo&key=AIzaSyBJdh8EzsmDv9kypTiI6hGCwmYl7_pMXec`; return fetch(uri).then(res => res.json()); }
return dispatch =>fetch(`https://api.projectoxford.ai/luis/v1/application/preview?id=0a4ead29-b2bc-482e-b6ef-c8a0756c07f4&subscription-key=c71fa1b6442b4c73ae3a60abb7bc251b&q=${searchterm}&contextid=${contextid}`) .then(response => response.json()) .then(json => dispatch(getTopScoringIntentandEntites(json)))
const getData = (dispatch, url, action) => { fetch(url) .then(response => response.json()) .then(data => dispatch(action(data))); }
function* fetchItemPrice(id,currency){ const response = yield fetch(`http://localhost:8081/prices/${currency}/${id}`); const json = yield response.json(); const price = json[0].price; yield put(setItemPrice(id,price)); }
/** * Fetches the JWT token. This token is cached for a default of 25mins. * If it is within 5mins or expiry it will fetch a new one. */ fetchJWT() { if (storedToken && storedToken.exp) { const diff = storedToken.exp - Math.trunc(new Date().getTime() / 1000); // refetch token if we are within 60s of it exp if (diff < CLOCK_SKEW_SECONDS) { tokenFetchPromise = null; } } if (!tokenFetchPromise) { tokenFetchPromise = fetch(`${UrlUtils.getJenkinsRootURL()}/jwt-auth/token`, { credentials: 'same-origin' }) .then(this.checkStatus) .then(response => { const token = response.headers.get('X-BLUEOCEAN-JWT'); if (token) { return token; } throw new Error('Could not fetch jwt_token'); }); } return tokenFetchPromise; }, /**
stopContainer: (image) => { let url = baseUrl+'/containers/'+image+'/stop'; return fetch(url) .then(image) }
products.map((product)=> { return fetch(`http://luisai.sachinkukreja.com/api/products/${product.id}?ws_key=K5JKXSHBIE76CXXY5V4KBWS6F156GS7N&output_format=JSON`) .then(response => response.json()) .then(json => productdetails.push(json.product)) })
return dispatch => { return fetch('/images') .then(response => response.json()) .then(json => dispatch(receiveCharacters(json))) }
return (dispatch) => { switch (topscoringIntent) { case "SearchProductCategory": if (entities.length == 1) { entity_type.map((type)=> { switch (type) { case "color": fetch(`http://luisai.sachinkukreja.com/api/search/?ws_key=K5JKXSHBIE76CXXY5V4KBWS6F156GS7N&query=${initialEntity} ${entities[0].entity}&language=1&output&output_format=JSON`) .then(response => response.json()) .then(json=> { dispatch(GetProducts(json.products,dialog)).then(()=> { dispatch(ProductReceived(productdetails)); UsePrevparams =false; },()=> { dispatch(ChatChanged("No Item Found , Please try some other color ")); UsePrevparams = true; }); }); break; case "brand": color = ""; actions[0].parameters.map((param)=> { if (param.name == "color" && param.value != null) { color = param.value[0].entity; } }); fetch(`http://luisai.sachinkukreja.com/api/search/?ws_key=K5JKXSHBIE76CXXY5V4KBWS6F156GS7N&query=${color} ${initialEntity} ${entities[0].entity}&language=1&output&output_format=JSON`) .then(response => response.json()) .then(json=> { dispatch(GetProducts(json.products,dialog)).then(()=> { dispatch(ProductReceived(productdetails)); UsePrevparams = false; } ,()=> { dispatch(ChatChanged("No Item Found , Please try some other brand ")); UsePrevparams = true; } ); }); break; case "builtin.ordinal": contextid =""; dispatch(callLuisApi(query)); break; default: fetch(`http://luisai.sachinkukreja.com/api/search/?ws_key=K5JKXSHBIE76CXXY5V4KBWS6F156GS7N&query=${entities[0].entity}&language=1&output&output_format=JSON`) .then(response => response.json()) .then(json=> { dispatch(GetProducts(json.products,dialog)).then(()=> { dispatch(ProductReceived(productdetails)) },()=> { dispatch(ChatChanged("No Item Found , Please try a different keyword")) }); }); break; } }); } else if (entities.length > 1) { let ConsolidatedEtities = ""; entities.map((entity)=> { ConsolidatedEtities += " " + entity.entity; }); fetch(`http://luisai.sachinkukreja.com/api/search/?ws_key=K5JKXSHBIE76CXXY5V4KBWS6F156GS7N&query=${ConsolidatedEtities}&language=1&output&output_format=JSON`) .then(response => response.json()) .then(json=> { dispatch(GetProducts(json.products,dialog)).then(()=> { dispatch(ProductReceived(productdetails)); initialEntity = ConsolidatedEtities; }); }) } else { contextid = ""; dispatch(callLuisApi(query)); } break; case "AddToCart": if (ProductSelected != null) { console.log("product selected", ProductSelected); return dispatch(ChatChanged(ProductSelected.name + " Added to Cart")); } else if (productdetails.length == 1) { console.log("only one product remains"); return dispatch(ChatChanged(productdetails[0].name + " Added to Cart")); }else if (productdetails.length >1 && entities.length >= 1) { let index = -1; entities.map((entity)=>{ if (entity.type == "builtin.ordinal") { index = ordinalDict[entity.entity]; } }); return dispatch(ChatChanged(productdetails[index].name + " Added to Cart")); } return dispatch(ChatChanged("No Product Selected ")); break; case "SortProducts": ChatChanged(enitities.toString() + " are the entites needed to sort "); break; case "None": return dispatch => dispatch(ChatChanged("Sorry, I Do not understand that ")); break; } }
return dispatch => { dispatch(requestSlackletes()); return fetch('https://slack-leaderboards.herokuapp.com/scores') .then(req=>req.json()) .then(json => dispatch(receiveSlackletes(json))) }
multi: true, value: [this.state.value], }); }, switchToSingle () { this.setState({ multi: false, value: this.state.value ? this.state.value[0] : null }); }, getUsers (input) { if (!input) { return Promise.resolve({ options: [] }); } return fetch(`https://api.github.com/search/users?q=${input}`) .then((response) => response.json()) .then((json) => { return { options: json.items }; }); }, gotoUser (value, event) { window.open(value.html_url); }, toggleBackspaceRemoves () { this.setState({ backspaceRemoves: !this.state.backspaceRemoves }); }, toggleCreatable () { this.setState({
export function fetchAttendees(dispatch) { let url = 'https://htn-interviews.firebaseio.com/users.json' return fetch(url) .then(req => req.json()) .then(json => dispatch(recieveJson(json))) }
return dispatch => { dispatch( requestLoadFile() ); return fetch( 'http://localhost:7171/base/' + name ) .then( response => response.json() ) .then( json => dispatch( recieveLoadFile( json ) ) ); };
return (dispatch) => { dispatch({ type: 'LOADING_CATS' }); return fetch('http://localhost:3000/db') .then(response => response.json()) .then(cats => dispatch({ type: 'FETCH_CATS', payload: cats.images })); };
function getJSON(url, customHeader = null, opts = {}) { const headers = defaultHeaders(customHeader); const defaultOpts = { method: 'GET', headers, mode: 'cors' }; const options = Object.assign(defaultOpts, opts); return fetch(url, options).then(res => res.json()); }
handleTransScore(){ const {test ,score, userInput, WordList} = this.state; let score_temp = 0; let countTestNumber = 0; for(countTestNumber = 0; countTestNumber< 3; countTestNumber++){ const {topic,wordcardsTag,testID,answer,userAns} = test[countTestNumber]; if(userAns === answer){ score_temp++; test.splice(countTestNumber,1,{ topic: topic, wordcardsTag: wordcardsTag, testID: testID, highlightQ: false, submitted: true, answer: answer, userAns: userAns, }) var now = new Date(); let nowString = date.format(now,'YYYY/MM/DD HH:mm:ss'); const {name, trans, testTime, number, total, inputTime} = WordList.wordcards[wordcardsTag]; const newTestTime = parseInt(testTime,10) - 1; WordList.wordcards.splice(wordcardsTag,1,{ name: name, trans: trans, testTime: newTestTime, number: number, total: total, updateTime: nowString, inputTime: inputTime }) }else{ test.splice(countTestNumber,1,{ topic: topic, wordcardsTag: wordcardsTag, testID: testID, highlightQ: true, submitted: true, answer: answer, userAns: userAns, }) var now = new Date(); let nowString = date.format(now,'YYYY/MM/DD HH:mm:ss'); const {name, trans, testTime, number, total, inputTime} = WordList.wordcards[wordcardsTag]; const newTestTime = parseInt(testTime,10) + 1; WordList.wordcards.splice(wordcardsTag,1,{ name: name, trans: trans, testTime: newTestTime, number: number, total: total, updateTime: nowString, inputTime: inputTime }) } } if(score_temp === 0)score_temp = 0; else if(score_temp === 1)score_temp = 60; else if(score_temp === 2)score_temp = 80; else if(score_temp === 3)score_temp = 100; else score_temp = -1; this.setState({ score: score_temp, test: test, WordList: WordList }); fetch('/api/wordreview',{ method: 'post', headers:{ 'Accept':'application/json', 'Content-Type':'application/json', }, body: JSON.stringify(WordList.wordcards), }); }