Revert "Handle BigNumber conversions in JSON properly (without loss of precision) (#71)" (#126)

* revert: revert "Handle BigNumber conversions in JSON properly (without loss of precision) (#71)"

This reverts commit e3866129b2b3cbd6e099fe4ab66319c4fe6ae485.

* fix: type errors

* fix: typescript errors in superset-ui-demo
This commit is contained in:
Christine Chambers 2019-04-02 14:32:15 -07:00 committed by Yongjie Zhao
parent fef6466f74
commit f71180e251
10 changed files with 23 additions and 99 deletions

View File

@ -86,6 +86,11 @@
"testEnvironment": "node"
}
]
},
"typescript": {
"include": [
"./storybook/**/*"
]
}
},
"workspaces": [

View File

@ -9,8 +9,11 @@ const defaultMockLoadFormData = jest.fn(allProps => Promise.resolve(allProps.for
// coerce here else get: Type 'Mock<Promise<any>, []>' is not assignable to type 'Mock<Promise<any>, any[]>'
let mockLoadFormData = defaultMockLoadFormData as jest.Mock<Promise<any>, any>;
const mockLoadDatasource = jest.fn(datasource => Promise.resolve(datasource));
const mockLoadQueryData = jest.fn(input => Promise.resolve(input));
const mockLoadDatasource = jest.fn(datasource => Promise.resolve(datasource)) as jest.Mock<
Promise<any>,
any
>;
const mockLoadQueryData = jest.fn(input => Promise.resolve(input)) as jest.Mock<Promise<any>, any>;
// ChartClient is now a mock
jest.mock('../../src/clients/ChartClient', () =>

View File

@ -32,7 +32,6 @@
},
"dependencies": {
"@babel/runtime": "^7.1.2",
"json-bigint": "^0.3.0",
"whatwg-fetch": "^2.0.4"
},
"publishConfig": {

View File

@ -1,4 +1,3 @@
import JSONbig from 'json-bigint';
import { ParseMethod, SupersetClientResponse } from '../types';
function rejectIfNotOkay(response: Response): Promise<Response> {
@ -7,15 +6,6 @@ function rejectIfNotOkay(response: Response): Promise<Response> {
return Promise.resolve<Response>(response);
}
function parseJson(text: string): any {
try {
return JSONbig.parse(text);
} catch (e) {
// if JSONbig.parse fails, it throws an object (not a proper Error), so let's re-wrap the message.
throw new Error(e.message);
}
}
export default function parseResponse(
apiPromise: Promise<Response>,
parseMethod: ParseMethod = 'json',
@ -27,9 +17,7 @@ export default function parseResponse(
} else if (parseMethod === 'text') {
return checkedPromise.then(response => response.text().then(text => ({ response, text })));
} else if (parseMethod === 'json') {
return checkedPromise.then(response =>
response.text().then(text => ({ json: parseJson(text), response })),
);
return checkedPromise.then(response => response.json().then(json => ({ json, response })));
}
throw new Error(`Expected parseResponse=null|json|text, got '${parseMethod}'.`);

View File

@ -1,22 +1,8 @@
import fetchMock from 'fetch-mock';
import { BigNumber } from 'bignumber.js';
import { SupersetClientClass, ClientConfig } from '../src';
import throwIfCalled from './utils/throwIfCalled';
import { LOGIN_GLOB } from './fixtures/constants';
/* NOTE: We're using fetchMock v6.5.2, but corresponding fetchMock type declaration files are only available for v6.0.2
* and v7+. It looks like there are behavior changes between v6 and v7 that break our tests, so upgrading to v7 is
* probably some work.
*
* To avoid this, we're using the type declarations for v6.0.2, but there is at least one API inconsistency between that
* type declaration file and the actual library we're using. It looks like `sendAsJson` was added sometime after that
* release, or else the type declaration file isn't completely accurate. To get around this, it's necessary to add
* a `@ts-ignore` decorator before references to `sendAsJson` (there's one instance of that in this file).
*
* The **right** solution is probably to upgrade to fetchMock v7 (and the latest type declaration) and fix the tests
* that become broken as a result.
*/
describe('SupersetClientClass', () => {
beforeAll(() => {
fetchMock.get(LOGIN_GLOB, { csrf_token: '' });
@ -138,9 +124,6 @@ describe('SupersetClientClass', () => {
it('does not set csrfToken if response is not json', () => {
fetchMock.get(LOGIN_GLOB, '123', {
overwriteRoutes: true,
// @TODO remove once fetchMock is upgraded to 7+, see note at top of this file
// @ts-ignore
sendAsJson: false,
});
return new SupersetClientClass({})
@ -267,8 +250,7 @@ describe('SupersetClientClass', () => {
const mockTextUrl = `${protocol}//${host}${mockTextEndpoint}`;
const mockPutUrl = `${protocol}//${host}${mockPutEndpoint}`;
const mockDeleteUrl = `${protocol}//${host}${mockDeleteEndpoint}`;
const mockBigNumber = '9223372036854775807';
const mockTextJsonResponse = `{ "value": ${mockBigNumber} }`;
const mockTextJsonResponse = '{ "value": 9223372036854775807 }';
fetchMock.get(mockGetUrl, { json: 'payload' });
fetchMock.post(mockPostUrl, { json: 'payload' });
@ -347,21 +329,6 @@ describe('SupersetClientClass', () => {
);
});
it('supports parsing a response as JSON while preserving precision of large numbers', () => {
expect.assertions(2);
const client = new SupersetClientClass({ protocol, host });
return client.init().then(() =>
client.get({ url: mockTextUrl }).then(({ json }) => {
expect(fetchMock.calls(mockTextUrl)).toHaveLength(1);
// @ts-ignore
expect(json.value.toString()).toBe(new BigNumber(mockBigNumber).toString());
return Promise.resolve();
}),
);
});
it('supports parsing a response as text', () => {
expect.assertions(2);
const client = new SupersetClientClass({ protocol, host });
@ -471,21 +438,6 @@ describe('SupersetClientClass', () => {
);
});
it('supports parsing a response as JSON while preserving precision of large numbers', () => {
expect.assertions(2);
const client = new SupersetClientClass({ protocol, host });
return client.init().then(() =>
client.post({ url: mockTextUrl }).then(({ json }) => {
expect(fetchMock.calls(mockTextUrl)).toHaveLength(1);
// @ts-ignore
expect(json.value.toString()).toBe(new BigNumber(mockBigNumber).toString());
return Promise.resolve();
}),
);
});
it('supports parsing a response as text', () => {
expect.assertions(2);
const client = new SupersetClientClass({ protocol, host });

View File

@ -63,7 +63,7 @@ describe('parseResponse()', () => {
.catch(error => {
expect(fetchMock.calls(mockTextUrl)).toHaveLength(1);
expect(error.stack).toBeDefined();
expect(error.message.includes('Unexpected')).toBe(true);
expect(error.message.includes('Unexpected token')).toBe(true);
return Promise.resolve();
});

View File

@ -51,5 +51,8 @@
"react": "^16.6.0",
"react-dom": "^16.6.0",
"storybook-addon-jsx": "^5.4.0"
},
"devDependencies": {
"@types/storybook__addon-knobs": "^4.0.4"
}
}

View File

@ -3,7 +3,7 @@ import { SupersetClient } from '@superset-ui/connection';
import ErrorMessage from './ErrorMessage';
export type Props = {
children: ({ payload }: { payload: object }) => ReactNode;
children: ({ payload }: { payload?: object }) => ReactNode;
endpoint?: string;
host: string;
method?: 'POST' | 'GET';
@ -16,7 +16,7 @@ type State = {
payload?: object;
};
export const renderError = error => (
export const renderError = (error: Error) => (
<div>
The following error occurred, make sure you have <br />
1) configured CORS in Superset to receive requests from this domain. <br />
@ -35,7 +35,7 @@ export default class VerifyCORS extends React.Component<Props, State> {
this.handleVerify = this.handleVerify.bind(this);
}
componentDidUpdate(prevProps) {
componentDidUpdate(prevProps: Props) {
const { endpoint, host, postPayload, method } = this.props;
if (
(this.state.didVerify || this.state.error) &&

View File

@ -0,0 +1,4 @@
declare module '@superset-ui/legacy-preset-chart-big-number';
declare module '@superset-ui/legacy-plugin-chart-sankey';
declare module '@superset-ui/legacy-plugin-chart-sunburst';
declare module '@superset-ui/legacy-plugin-chart-word-cloud';

View File

@ -1,30 +0,0 @@
declare module 'json-bigint' {
interface JSONbig {
/**
* Converts a JavaScript Object Notation (JSON) string into an object, preserving precision for numeric values.
* @param text A valid JSON string.
* @param reviver A function that transforms the results. This function is called for each member of the object.
* If a member contains nested objects, the nested objects are transformed before the parent object is.
*/
parse(text: string, reviver?: (key: any, value: any) => any): any;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string, preserving precision for numeric values.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results, or an array of strings and numbers that acts
* as a approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(
value: any,
replacer?: (number | string)[] | null | ((key: string, value: any) => any),
space?: string | number,
): string;
}
/**
* An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
*/
const JSONbig: JSONbig;
export = JSONbig;
}