Skip to content

Instantly share code, notes, and snippets.

@faustoct
Created Jul 6, 2020
Embed
What would you like to do?
Backend requests
import { AsyncStorage } from 'react-native'
import Location from './Location.js'
class Backend {
static get = async (url,params,callback) => {
let p = ''
params = (params ? params : {})
const {location, status} = await Location.getAsync();
if(!location)return;
let endpoint = null
try {
if(location && Object.keys(location).length>0){
params['location'] = JSON.stringify(location)
}
if(params){
p = Object.keys(params).map(function(k) {
return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`
}).join('&')
}
endpoint = `${url}?${p}`
let response = await fetch(
endpoint,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'token': this.token
}
}
)
let json = await response.json();
if(callback)callback(json)
} catch (error) {
//alert(`Backend get: ${error} : ${endpoint} : ${params}`)
//console.error(error);
}
}
static post = async (url, params, callback) => {
params = (params ? params : {})
const {location, status} = await Location.getAsync();
//if(!location)return
let endpoint = null
try {
if(location && Object.keys(location).length>0){
params['location'] = JSON.stringify(location)
}
let response = await fetch(
url,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'token': this.token
},
body: JSON.stringify(params)
}
);
let json = await response.json();
if(callback)callback(json)
} catch (error) {
}
}
}
export default Backend;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment