Skip to content

Commit bdb337d

Browse files
committed
Add utility to support json stringify/parse with JSONBigInt
fixes #57 Example Usages: // Usage with normalizer import { Experiment } from 'tsp-typescript-client/lib/models/experiment'; let input = JSONBigUtils.stringify(experiment); let output: Experiment = JSONBigUtils.parse(input, Experiment); // Usage no normalizer input = JSONBigUtils.stringify(inputObj); output = JSONBigUtils.parse<string>(input); input = JSONBigUtils.stringify(BigInt("1234567890123456789")); output = JSONBigUtils.parse<bigint>(bigIntInput); Signed-off-by: Bernd Hufmann <bernd.hufmann@ericsson.com>
1 parent bab2aa3 commit bdb337d

File tree

2 files changed

+114
-0
lines changed

2 files changed

+114
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// tslint:disable: no-unused-expression
2+
3+
import { Experiment } from '../models/experiment';
4+
import { Identifier } from '../models/identifier';
5+
import { Query } from '../models/query/query';
6+
import { HttpRequest, HttpResponse, RestClient } from '../protocol/rest-client';
7+
import { FixtureSet } from '../protocol/test-utils';
8+
import { TspClient } from '../protocol/tsp-client';
9+
import { JSONBigUtils } from './jsonbig-utils';
10+
11+
describe('JSONBigUtils tests', () => {
12+
13+
const client = new TspClient('not-relevant');
14+
const httpRequestMock = jest.fn<Promise<HttpResponse>, [req: HttpRequest]>();
15+
16+
let fixtures: FixtureSet;
17+
18+
beforeAll(async () => {
19+
fixtures = await FixtureSet.fromFolder(__dirname, '../../fixtures/tsp-client');
20+
RestClient['httpRequest'] = httpRequestMock;
21+
});
22+
23+
beforeEach(() => {
24+
httpRequestMock.mockReset();
25+
httpRequestMock.mockResolvedValue({ text: '', status: 404, statusText: 'Not found' });
26+
});
27+
28+
it('testJSONBigUtils-with-normalizer', async () => {
29+
httpRequestMock.mockReturnValueOnce(fixtures.asResponse('create-experiment-0.json'));
30+
const response = await client.createExperiment(new Query({}));
31+
const experiment = response.getModel()!;
32+
33+
const input = JSONBigUtils.stringify(experiment);
34+
const experiment2: Experiment = JSONBigUtils.parse(input, Experiment);
35+
36+
expect(experiment).toEqual(experiment2);
37+
});
38+
39+
it('testJSONBigUtils-no-normalizer', async () => {
40+
const inputObj = 'hallo';
41+
const input = JSONBigUtils.stringify(inputObj);
42+
const output = JSONBigUtils.parse<string>(input);
43+
expect(typeof output).toEqual('string');
44+
45+
let bigIntObj = BigInt("1234567890123456789");
46+
const bigIntInput = JSONBigUtils.stringify(bigIntObj);
47+
const bigIntOutput = JSONBigUtils.parse<bigint>(bigIntInput);
48+
expect(typeof bigIntOutput).toEqual('bigint');
49+
50+
const idObj: Identifier = {
51+
version: "version",
52+
buildTime: "buildTime",
53+
os: "os",
54+
osArch: "osArch",
55+
osVersion: "osVersion",
56+
cpuCount: "cpuCount",
57+
maxMemory: "maxMemory",
58+
launcherName: "launcherName",
59+
productId: "productId"
60+
};
61+
const idInput = JSONBigUtils.stringify(idObj);
62+
const idOutput: Identifier = JSONBigUtils.parse<Identifier>(idInput);
63+
expect(typeof idOutput).toEqual('object');
64+
expect(idOutput).toEqual(idObj);
65+
});
66+
});
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { Normalizer } from '../protocol/serialization';
2+
import JSONBigConfig = require('json-bigint');
3+
4+
const JSONBig = JSONBigConfig({
5+
useNativeBigInt: true,
6+
});
7+
8+
/**
9+
* Rest client helper to make request.
10+
* The request response status code indicates if the request is successful.
11+
* The json object in the response may be undefined when an error occurs.
12+
*/
13+
export class JSONBigUtils {
14+
15+
static parse<T>(url: string): T;
16+
static parse<T>(input: string, normalizer?: Normalizer<T>): T;
17+
/**
18+
* Parse JSON-encoded data using a normalizer. It will create `BigInt'
19+
* values instead of `number` as defined by normalizer.
20+
*
21+
* @template T is the expected type of the json object returned
22+
* @param input Input JSON string to deserialize
23+
* @param normalizer Normalizer to create type T
24+
*/
25+
public static parse<T>(input: string, normalizer?: Normalizer<T>) {
26+
try {
27+
const parsed = JSONBig.parse(input);
28+
try {
29+
if (normalizer) {
30+
return normalizer(parsed) as T;
31+
}
32+
return parsed as T;
33+
} catch (err) {
34+
console.log('Error normalizing parsed input string: ' + err.toString());
35+
}
36+
} catch (err) {
37+
console.log('Error parsing input string: ' + JSON.stringify(err));
38+
}
39+
return null;
40+
}
41+
42+
/**
43+
* Stringify JS objects. Can stringify `BigInt` values.
44+
*/
45+
public static stringify(data: any): string {
46+
return JSONBig.stringify(data);
47+
}
48+
}

0 commit comments

Comments
 (0)