@sheenarbw/redux-drf-sagas
Version:
If you are running Django Rest Framework on your backend then you can use these tools to get your js frontend to play nice with your backend. It's framework agnostic. It doesn't mean you would need to use redux as your main state management tool
85 lines (69 loc) • 1.82 kB
JavaScript
import { getAuthToken } from './authTokenStorage.js';
const _toCamel = s => {
return s.replace(/([-_][a-z])/gi, $1 => {
return $1.toUpperCase().replace('-', '').replace('_', '');
});
};
const _isArray = function (a) {
return Array.isArray(a);
};
const _isObject = function (o) {
return o === Object(o) && !_isArray(o) && typeof o !== 'function';
};
const fromSnakeToCamel = function (o) {
if (_isObject(o)) {
const n = {};
Object.keys(o).forEach(k => {
n[_toCamel(k)] = fromSnakeToCamel(o[k]);
});
return n;
} else if (_isArray(o)) {
return o.map(i => {
return fromSnakeToCamel(i);
});
}
return o;
};
const camelStringToSnake = function (s) {
return s
.replace(/(?:^|\.?)([A-Z])/g, function (x, y) {
return '_' + y.toLowerCase();
})
.replace(/^_/, '');
};
export async function fetchAndClean({ url, method, data, noResponseJson }) {
const headers = {
'Content-Type': 'application/json',
};
const token = getAuthToken();
if (token) headers.Authorization = `Token ${token}`;
const params = {
method: method || 'GET',
headers,
};
if (data) {
const snakeData = {};
Object.keys(data).forEach(key => {
snakeData[camelStringToSnake(key)] = data[key];
});
params['body'] = JSON.stringify(snakeData);
}
const response = await fetch(url, params);
if (noResponseJson) {
return Promise.resolve({
response,
responseData: {},
});
}
const responseData = await response.json();
return Promise.resolve({
response,
responseData: fromSnakeToCamel(responseData),
});
}
export function getNextPageNumberFromUrl({ url }) {
if (url === null) return null;
const urlInstance = new URL(url);
const page = urlInstance.searchParams.get('page');
return page;
}