Skip to content

Instantly share code, notes, and snippets.

@johnwmcarneiro
Last active May 1, 2019 14:53
Show Gist options
  • Save johnwmcarneiro/b2d9f9115151dde802e0608f32ac4229 to your computer and use it in GitHub Desktop.
Save johnwmcarneiro/b2d9f9115151dde802e0608f32ac4229 to your computer and use it in GitHub Desktop.
Example abstract fetch
/**
* Created by @johnwmcarneiro 30/04/2019
*
* Requires:
* - querystring
*/
'use strict';
const { stringify } = require('querystring');
import { PROD_BASE_URL, DEV_BASE_URL } from './env.config';
let baseURL = PROD_BASE_URL;
if (__DEV__) {
baseURL = DEV_BASE_URL;
}
export const BASE_URL = baseURL + '/api/v1';
export default class Api {
static userToken = null;
static setUserToken(token) {
this.userToken = token;
}
static resetUserToken() {
this.userToken = null;
}
static async request(endpoint, customOptions = {}) {
const standardOptions = {
method: "GET",
requireAuth: true,
data: {},
headers: {}
};
let options = Object.assign({}, standardOptions, customOptions);
let headers = new Headers(Object.assign({}, {
Accept: "application/json",
"Content-Type": "application/json"
}, options.headers));
if (options.requireAuth) {
headers.set("X-User-Token", this.userToken);
}
let uri = BASE_URL + endpoint;
let method = options.method;
let data = options.data;
let fetchOptions = { method: method, headers: headers };
if (method === "GET" || method === "DELETE") {
uri += "?" + stringify(data);
} else {
if (data instanceof FormData) {
fetchOptions.body = data;
} else {
fetchOptions.body = JSON.stringify(data);
}
}
if (__DEV__) {
console.info(`Call api: ${uri} with options ${JSON.stringify(fetchOptions)}`);
}
let response = await fetch(uri, fetchOptions);
try {
return await response.json();
} catch (e) {
return {};
}
}
}
export const PROD_BASE_URL = 'http://api.production.com';
export const DEV_BASE_URL = 'http://192.168.0.1:3000';
import Api from 'api';
Api.setToken('TOKEN');
Api.request('/posts'); // GET
Api.request('/posts', { method: 'POST', data: { name: 'John' } }); // POST
Api.request('/posts', { method: 'PUT', data: { name: 'John' } }); // PUT
// With FormData
let data = new FormData();
data.append('name', 'John');
data.append('emails[]', 'johnwmcarneiro@gmail.com');
data.append('emails[]', 'contato@capapreta.com.br');
Api.request('/users', { method: 'POST', data: data });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment