-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
graphql-server.ts
74 lines (64 loc) · 2.08 KB
/
graphql-server.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
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- ignore type errors from `graphql` package
// @ts-nocheck
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { createServer, Server, IncomingMessage, ServerResponse } from 'http';
import { buildSchema, introspectionFromSchema } from 'graphql';
const sdlSchema = readFileSync(resolve(__dirname, 'user-schema.graphql'), 'utf8');
const graphqlSchemaObj = buildSchema(sdlSchema);
const introspectionQueryResult = introspectionFromSchema(graphqlSchemaObj);
class TestGraphQLServer {
private server: Server;
private base: string;
constructor(private port = 1337) {
this.server = createServer(this.router.bind(this));
this.base = `http://localhost:${this.port}`;
}
start(): Promise<{ url: string }> {
return new Promise(resolve => {
this.server.listen(this.port, () => {
resolve({ url: this.base });
});
});
}
stop(): Promise<void> {
return new Promise((resolve, reject) => {
this.server.close(err => {
err ? reject(err) : resolve();
});
});
}
private async router(req: IncomingMessage, res: ServerResponse): Promise<void> {
const { pathname } = new URL(req.url, this.base);
if (pathname === '/') {
const { query } = await this.parseData(req);
if (query.includes('query IntrospectionQuery')) {
res.end(JSON.stringify({
data: introspectionQueryResult
}));
}
} else if (pathname === '/my-headers') {
res.end(JSON.stringify(req.headers));
}
}
private parseData(req: IncomingMessage): Promise<any | string> {
return new Promise(resolve => {
let data = '';
req.on('data', chunk => {
data += chunk;
});
req.on('end', () => {
if (req.headers['content-type'] === 'application/json') {
resolve(JSON.parse(data));
} else {
resolve(data);
}
});
});
}
}
const graphqlServer = new TestGraphQLServer();
graphqlServer.start().then(({ url }) => {
// eslint-disable-next-line no-console
console.log(url);
});