Skip to content

Commit e836dcd

Browse files
author
Paul Korzhyk
committed
Custom JSON parser support
1 parent 1837d8d commit e836dcd

File tree

4 files changed

+85
-45
lines changed

4 files changed

+85
-45
lines changed

src/clientStub.ts

+21-8
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,26 @@ const AUTO_REFRESH_PREFETCH_TIME = 5000;
2626
export class DgraphClientStub {
2727
private readonly addr: string;
2828
private readonly options: Options;
29+
// tslint:disable-next-line no-any
30+
private readonly jsonParser: (text: string) => any;
2931
private legacyApi: boolean;
3032
private accessToken: string;
3133
private refreshToken: string;
3234
private autoRefresh: boolean;
3335
private autoRefreshTimer?: number;
3436

35-
constructor(addr?: string, legacyApi?: boolean, options?: Options) {
37+
constructor(
38+
addr?: string,
39+
stubConfig: {
40+
legacyApi?: boolean;
41+
// tslint:disable-next-line no-any
42+
jsonParser?(text: string): any;
43+
} = {},
44+
options?: Options,
45+
) {
3646
if (addr === undefined) {
37-
this.addr = "http://localhost:8080"; // tslint:disable-line no-http-string
47+
// tslint:disable-next-line no-http-string
48+
this.addr = "http://localhost:8080";
3849
} else {
3950
this.addr = addr;
4051
}
@@ -45,7 +56,12 @@ export class DgraphClientStub {
4556
this.options = options;
4657
}
4758

48-
this.legacyApi = !!legacyApi;
59+
this.legacyApi = !!stubConfig.legacyApi;
60+
this.jsonParser =
61+
stubConfig.jsonParser !== undefined
62+
? stubConfig.jsonParser
63+
: // tslint:disable-next-line no-unsafe-any
64+
JSON.parse.bind(JSON);
4965
}
5066

5167
public async detectApiVersion(): Promise<string> {
@@ -382,10 +398,7 @@ export class DgraphClientStub {
382398
);
383399
}
384400

385-
private async callAPI<T>(
386-
path: string,
387-
config: Config,
388-
): Promise<T> {
401+
private async callAPI<T>(path: string, config: Config): Promise<T> {
389402
const url = this.getURL(path);
390403
if (this.accessToken !== undefined && path !== "login") {
391404
config.headers = config.headers !== undefined ? config.headers : {};
@@ -407,7 +420,7 @@ export class DgraphClientStub {
407420

408421
try {
409422
// tslint:disable-next-line no-unsafe-any
410-
json = JSON.parse(responseText);
423+
json = this.jsonParser(responseText);
411424
} catch (e) {
412425
if (config.acceptRawText) {
413426
return <T>(<unknown>responseText);

tests/clientStub.spec.ts

+39-16
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,32 @@
11
import * as dgraph from "../src";
22
import { Request } from "../src/types";
33

4-
import { setup } from "./helper";
4+
import { SERVER_ADDR, setup } from "./helper";
55

66
async function checkHealth(stub: dgraph.DgraphClientStub): Promise<void> {
7-
await expect(stub.getHealth()).resolves.toHaveProperty("0.status", "healthy");
7+
await expect(stub.getHealth()).resolves.toHaveProperty(
8+
"0.status",
9+
"healthy",
10+
);
811
}
912

1013
describe("clientStub", () => {
1114
describe("constructor", () => {
1215
it("should accept undefined argument", async () => {
1316
await checkHealth(new dgraph.DgraphClientStub());
1417
});
18+
it("should accept custom JSON parser", async () => {
19+
const mockParser = jest.fn((input: string) => ({ input }));
20+
const stub = new dgraph.DgraphClientStub(SERVER_ADDR, {
21+
jsonParser: mockParser,
22+
});
23+
await expect(
24+
stub.query({
25+
query: "{ q(func: uid(1)) { uid } }",
26+
}),
27+
).resolves.toBeTruthy();
28+
expect(mockParser.mock.calls.length).toBe(1);
29+
});
1530
});
1631

1732
describe("health", () => {
@@ -24,9 +39,9 @@ describe("clientStub", () => {
2439
describe("fetchUiKeywords", () => {
2540
it("should return keywords object", async () => {
2641
const client = await setup();
27-
await expect(client.anyClient().fetchUiKeywords())
28-
.resolves
29-
.toHaveProperty("keywords");
42+
await expect(
43+
client.anyClient().fetchUiKeywords(),
44+
).resolves.toHaveProperty("keywords");
3045
const resp = await client.anyClient().fetchUiKeywords();
3146
expect(resp.keywords).toContainEqual({
3247
type: "",
@@ -53,7 +68,9 @@ describe("clientStub", () => {
5368
// tslint:disable-next-line no-any
5469
expect((<any>stub).callAPI).toHaveBeenCalledTimes(1);
5570
// tslint:disable-next-line no-unsafe-any no-any
56-
expect((<any>stub).callAPI.mock.calls[0][0]).toContain("timeout=777s");
71+
expect((<any>stub).callAPI.mock.calls[0][0]).toContain(
72+
"timeout=777s",
73+
);
5774

5875
req.timeout = 0;
5976
req.startTs = 0;
@@ -80,8 +97,10 @@ describe("clientStub", () => {
8097
// tslint:disable-next-line no-any
8198
expect((<any>stub).callAPI).toHaveBeenCalledTimes(1);
8299
// tslint:disable-next-line no-unsafe-any no-any
83-
expect((<any>stub).callAPI.mock.calls[0][1].headers)
84-
.toHaveProperty("Content-Type", "application/rdf");
100+
expect((<any>stub).callAPI.mock.calls[0][1].headers).toHaveProperty(
101+
"Content-Type",
102+
"application/rdf",
103+
);
85104

86105
await stub.mutate({
87106
mutation: '{ "setJson": { "name": "Alice" } }',
@@ -90,9 +109,10 @@ describe("clientStub", () => {
90109
// tslint:disable-next-line no-any
91110
expect((<any>stub).callAPI).toHaveBeenCalledTimes(2);
92111
// tslint:disable-next-line no-unsafe-any no-any
93-
expect((<any>stub).callAPI.mock.calls[1][1].headers)
94-
.toHaveProperty("Content-Type", "application/json");
95-
112+
expect((<any>stub).callAPI.mock.calls[1][1].headers).toHaveProperty(
113+
"Content-Type",
114+
"application/json",
115+
);
96116
});
97117

98118
it("should use specified Content-Type if present", async () => {
@@ -108,8 +128,10 @@ describe("clientStub", () => {
108128
// tslint:disable-next-line no-any
109129
expect((<any>stub).callAPI).toHaveBeenCalledTimes(1);
110130
// tslint:disable-next-line no-unsafe-any no-any
111-
expect((<any>stub).callAPI.mock.calls[0][1].headers)
112-
.toHaveProperty("Content-Type", "application/json");
131+
expect((<any>stub).callAPI.mock.calls[0][1].headers).toHaveProperty(
132+
"Content-Type",
133+
"application/json",
134+
);
113135

114136
await stub.mutate({
115137
mutation: '{ "setJson": { "name": "Alice" } }',
@@ -119,9 +141,10 @@ describe("clientStub", () => {
119141
// tslint:disable-next-line no-any
120142
expect((<any>stub).callAPI).toHaveBeenCalledTimes(2);
121143
// tslint:disable-next-line no-unsafe-any no-any
122-
expect((<any>stub).callAPI.mock.calls[1][1].headers)
123-
.toHaveProperty("Content-Type", "application/rdf");
124-
144+
expect((<any>stub).callAPI.mock.calls[1][1].headers).toHaveProperty(
145+
"Content-Type",
146+
"application/rdf",
147+
);
125148
});
126149
});
127150

tests/helper.ts

+19-17
Original file line numberDiff line numberDiff line change
@@ -4,38 +4,40 @@ export const SERVER_ADDR = "http://localhost:8080"; // tslint:disable-line no-ht
44
export const USE_LEGACY_API = false;
55

66
export function createClient(): dgraph.DgraphClient {
7-
return new dgraph.DgraphClient(new dgraph.DgraphClientStub(SERVER_ADDR, USE_LEGACY_API));
7+
return new dgraph.DgraphClient(
8+
new dgraph.DgraphClientStub(SERVER_ADDR, { legacyApi: USE_LEGACY_API }),
9+
);
810
}
911

10-
export function setSchema(c: dgraph.DgraphClient, schema: string): Promise<dgraph.Payload> {
12+
export function setSchema(
13+
c: dgraph.DgraphClient,
14+
schema: string,
15+
): Promise<dgraph.Payload> {
1116
return c.alter({ schema });
1217
}
1318

1419
export function dropAll(c: dgraph.DgraphClient): Promise<dgraph.Payload> {
1520
return c.alter({ dropAll: true });
1621
}
1722

18-
export async function setup(userid?: string, password?: string): Promise<dgraph.DgraphClient> {
23+
export async function setup(
24+
userid?: string,
25+
password?: string,
26+
): Promise<dgraph.DgraphClient> {
1927
const c = createClient();
2028
if (!USE_LEGACY_API) {
21-
if (userid === undefined) {
22-
await c.login("groot", "password");
23-
} else {
24-
await c.login(userid, password);
25-
}
29+
if (userid === undefined) {
30+
await c.login("groot", "password");
31+
} else {
32+
await c.login(userid, password);
33+
}
2634
}
2735
await dropAll(c);
2836
return c;
2937
}
3038

3139
export function wait(time: number): Promise<void> {
32-
return new Promise((resolve: (value?: void | PromiseLike<void>) => void): void => {
33-
const id = setTimeout(
34-
() => {
35-
clearTimeout(id);
36-
resolve();
37-
},
38-
time,
39-
);
40-
});
40+
return new Promise(
41+
(resolve: () => void): void => setTimeout(resolve, time),
42+
);
4143
}

tests/integration/versionDetect.spec.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ import { SERVER_ADDR, USE_LEGACY_API } from "../helper";
44

55
describe("clientStub version detection", () => {
66
it("should not throw errors", () => {
7-
const stub = new DgraphClientStub(SERVER_ADDR, USE_LEGACY_API);
8-
return expect(stub.detectApiVersion())
9-
.resolves
10-
.toMatch(/^v[0-9]+(.[0-9]+){2}.*/);
7+
const stub = new DgraphClientStub(SERVER_ADDR, {
8+
legacyApi: USE_LEGACY_API,
9+
});
10+
return expect(stub.detectApiVersion()).resolves.toMatch(
11+
/^v[0-9]+(.[0-9]+){2}.*/,
12+
);
1113
});
1214
});

0 commit comments

Comments
 (0)