-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathgraphQLClientServer.ts
79 lines (74 loc) · 2.2 KB
/
graphQLClientServer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import mock, { proxy } from 'xhr-mock';
import handleRequestFactory from './handleRequest';
import type { Data } from './types';
/**
* Starts a GraphQL Server in your browser: intercepts every call to http://localhost:3000/graphql
* and returns a response from the supplied data.
*
* @export A sinon.js FakeServer (http://sinonjs.org/releases/v2.3.6/fake-xhr-and-server/#fake-server)
* @param {any} data
* @param {any} url Specifies the endpoint to intercept (Default is 'http://localhost:3000/graphql').
*
* @example
* const data = {
* "posts": [
* {
* "id": 1,
* "title": "Lorem Ipsum",
* "views": 254,
* "user_id": 123,
* },
* {
* "id": 2,
* "title": "Sic Dolor amet",
* "views": 65,
* "user_id": 456,
* },
* ],
* "users": [
* {
* "id": 123,
* "name": "John Doe"
* },
* {
* "id": 456,
* "name": "Jane Doe"
* }
* ],
* };
*
* GraphQLClientServer(data);
* GraphQLClientServer(data, 'http://localhost:8080/api/graphql');
*/
export default function ({ data, url }: { data: Data; url: string }) {
const handleRequest = handleRequestFactory(data);
return {
start() {
// Intercept all XmlHttpRequest
mock.setup();
// Only handle POST request to the specified url
mock.post(
url,
(req, res) =>
new Promise((resolve) => {
handleRequest(url, {
body: req.body(),
}).then((response) => {
res.status(response.status);
res.headers(response.headers);
res.body(response.body);
resolve(res);
});
}),
);
// Ensure all other requests are handled by the default XmlHttpRequest
mock.use(proxy);
},
stop() {
mock.teardown();
},
getHandler() {
return handleRequest;
},
};
}