-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
217 lines (195 loc) · 5.89 KB
/
server.ts
File metadata and controls
217 lines (195 loc) · 5.89 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import http from 'http';
import connect from 'connect';
import { graphql, buildSchema } from 'graphql';
/*
|--------------------------------------------------------------------------
| GraphQL Schema Definition (SDL)
|--------------------------------------------------------------------------
| The schema describes:
| - Object types (User, Message)
| - Entry points (Query, Mutation)
| - Available fields and arguments
|
| buildSchema is used instead of makeExecutableSchema
| to keep the server minimal and dependency-free.
*/
const schema = buildSchema(`
type User {
id: ID!
name: String!
email: String!
}
type Message {
message: String!
timestamp: String!
}
type Query {
hello: String!
users: [User!]!
user(id: ID!): User
}
type Mutation {
sendMessage(message: String!): Message!
}
`);
/*
|--------------------------------------------------------------------------
| In-memory Data Store (Mock Database)
|--------------------------------------------------------------------------
| This is a simple in-process data source.
| In real-world applications this would be replaced by:
| - a database
| - a microservice call
| - or a repository layer
*/
const USERS = [
{ id: '1', name: 'Alice', email: 'alice@example.com' },
{ id: '2', name: 'Bob', email: 'bob@example.com' },
{ id: '3', name: 'Carol', email: 'carol@example.com' },
];
/*
|--------------------------------------------------------------------------
| Root Resolver Map
|--------------------------------------------------------------------------
| Each function corresponds to a field in Query or Mutation.
| Resolvers are executed lazily only when requested by the client.
|
| rootValue is used instead of per-type resolvers
| to keep the example максимально простым.
*/
const root = {
hello: () => 'Hello from GraphQL!',
users: () => USERS,
user: ({ id }: { id: string }) => USERS.find(u => u.id === id),
sendMessage: ({ message }: { message: string }) => ({
message,
timestamp: new Date().toISOString(),
}),
};
/*
|--------------------------------------------------------------------------
| Embedded GraphiQL UI
|--------------------------------------------------------------------------
| Served at GET /
| Provides an in-browser IDE for:
| - writing queries
| - running mutations
| - schema introspection
|
| No external backend dependencies required.
*/
const graphiqlHTML = `
<!DOCTYPE html>
<html>
<head>
<title>Node.js GraphQL Server</title>
<link href="https://unpkg.com/graphiql@2.2.0/graphiql.min.css" rel="stylesheet" />
</head>
<body style="margin:0;height:100vh">
<div id="graphiql" style="height:100vh"></div>
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/graphiql@2.2.0/graphiql.min.js"></script>
<script>
// GraphQL HTTP fetcher used by GraphiQL
const fetcher = params =>
fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(params),
}).then(res => res.json());
// Mount GraphiQL UI
ReactDOM.render(
React.createElement(GraphiQL, { fetcher }),
document.getElementById('graphiql')
);
</script>
</body>
</html>
`;
/*
|--------------------------------------------------------------------------
| Minimal JSON Body Parser Middleware
|--------------------------------------------------------------------------
| Implemented manually to avoid external dependencies.
| - Consumes request stream
| - Parses JSON payload
| - Attaches result to req.body
|
| This middleware is intentionally POST-only.
*/
function jsonBodyParser(req: any, res: any, next: any) {
if (req.method !== 'POST') return next();
let body = '';
req.on('data', (chunk: Buffer) => {
body += chunk.toString();
});
req.on('end', () => {
try {
req.body = JSON.parse(body || '{}');
next();
} catch {
res.statusCode = 400;
res.end('Invalid JSON payload');
}
});
}
/*
|--------------------------------------------------------------------------
| Connect Application
|--------------------------------------------------------------------------
| Connect is a low-level middleware framework.
| Unlike Express, it supports only:
| app.use(fn)
| app.use(path, fn)
|
| Each middleware is a single function.
*/
const app = connect();
/*
|--------------------------------------------------------------------------
| GraphiQL Middleware
|--------------------------------------------------------------------------
| GET / → serves GraphiQL UI
*/
app.use('/', (req: any, res: any, next: any) => {
if (req.method === 'GET' && req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.end(graphiqlHTML);
} else {
next();
}
});
/*
|--------------------------------------------------------------------------
| GraphQL Endpoint Middleware Chain
|--------------------------------------------------------------------------
| POST /graphql
| 1) JSON body parsing
| 2) GraphQL execution
*/
app.use('/graphql', jsonBodyParser);
app.use('/graphql', async (req: any, res: any) => {
if (req.method !== 'POST') {
res.statusCode = 405;
return res.end();
}
const { query, variables } = req.body;
const result = await graphql({
schema,
source: query,
rootValue: root,
variableValues: variables,
});
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(result));
});
/*
|--------------------------------------------------------------------------
| HTTP Server Bootstrap
|--------------------------------------------------------------------------
| The Connect app is passed directly into Node's HTTP server.
*/
http.createServer(app).listen(8080, () => {
console.log('🚀 Server running at http://localhost:8080/');
});