codekingpro/portable-devtools
115k
1/////////////////////////////////////////////////////////////2//3// pgAdmin 4 - PostgreSQL Tools4//5// Copyright (C) 2013 - 2024, The pgAdmin Development Team6// This software is released under the PostgreSQL Licence7//8//////////////////////////////////////////////////////////////9 10import pgAdmin from 'sources/pgadmin';11import gettext from 'sources/gettext';12import axios from 'axios';13 14/* Get the axios instance to call back end APIs.15Do not import axios directly, instead use this */16export default function getApiInstance(headers={}) {17 return axios.create({18 headers: {19 'Content-type': 'application/json',20 [pgAdmin.csrf_token_header]: pgAdmin.csrf_token,21 ...headers,22 }23 });24}25 26export function parseApiError(error, withData=false) {27 if (error.response) {28 // The request was made and the server responded with a status code29 // that falls out of the range of 2xx30 if(error.response.headers['content-type'] == 'application/json') {31 let err_resp_data = error.response.data;32 if (err_resp_data.response != undefined && Array.isArray(err_resp_data.response.errors)) {33 return err_resp_data.response.errors[0];34 } else {35 let errormsg = err_resp_data.errormsg;36 let data = error.response.data.data;37 // If we want to use data which came with error set withData38 // flag to true.39 return withData ? {errormsg, data} : errormsg;40 }41 } else {42 return error.response.statusText;43 }44 } else if (error.request) {45 // The request was made but no response was received46 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of47 // http.ClientRequest in node.js48 return gettext('Connection to pgAdmin server has been lost');49 } else if(error.message) {50 // Something happened in setting up the request that triggered an Error51 return error.message;52 } else if(error.errormsg) {53 // Received response JSON in socket handle54 return error.errormsg;55 } else {56 return error;57 }58}59 60export function callFetch(url, options, headers={}) {61 return fetch(url, {62 ...options,63 headers: {64 'Content-type': 'application/json',65 [pgAdmin.csrf_token_header]: pgAdmin.csrf_token,66 ...headers,67 }68 });69}70 