-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpServer.ts
216 lines (177 loc) · 7.37 KB
/
HttpServer.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
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
import * as Http from "http";
import * as Path from "path";
import * as Util from "util";
import * as Url from "url";
import * as FS from "fs";
import * as HttpStatusCodes from "http-status-codes";
import {IServer} from "./IServer";
import {Config} from "./Config";
import {IDbProcessor} from "./IDbProcessor";
import {DbCommand} from "./DbCommand";
import {Search} from "./Search";
import {ArgumentNullError} from "./ArgumentNullError";
export class HttpServer implements IServer {
private actionMap = {
"GET": this.processGetAction.bind(this),
"POST": this.processPostAction.bind(this),
"PUT": this.processPutAction.bind(this),
"DELETE": this.processDeleteAction.bind(this)
};
private config: Config;
private server: Http.Server;
private dbProcessor: IDbProcessor;
constructor(config: Config, dbProcessor: IDbProcessor) {
if (!config) throw new ArgumentNullError("config");
if (!dbProcessor) throw new ArgumentNullError("dbProcessor");
this.config = config;
this.dbProcessor = dbProcessor;
this.server = Http.createServer(this.handleRequest.bind(this));
}
public run(callback?: () => any): void {
this.server.listen(this.config.port, () => {
console.log("Server listening on port %s.", this.config.port);
if (callback)
callback();
});
}
public stop(callback?: () => any): void {
this.server.close(callback);
}
private handleRequest(request: Http.IncomingMessage, response: Http.ServerResponse) {
if (request.url === "/") {
response.statusCode = HttpStatusCodes.NO_CONTENT;
response.end();
}
else
this.processDbRequest(request, response);
}
private processDbRequest(request: Http.IncomingMessage, response: Http.ServerResponse) {
var dbCommand = DbCommand.parseRequest(this.config.dataPath, request);
if (dbCommand == null)
return this.badRequest(response, Util.format("Could not extract intended command from the url \"%s\".", request.url));
var dbPath = dbCommand.getDbRootPath();
var dbReady = () => {
var action = this.actionMap[request.method];
if (action == null)
throw Error(Util.format("Unhandled method '%s'.", request.method));
try {
action(dbCommand, request, response);
}
catch (err) {
this.badRequest(response, err);
}
};
FS.exists(dbPath, (exists: boolean) => {
if (!exists)
FS.mkdir(dbPath, 770, () => dbReady());
else
dbReady();
});
}
private processGetAction(dbCommand: DbCommand, request: Http.IncomingMessage, response: Http.ServerResponse) {
if (!dbCommand.hasEntityId()) {
var search = Search.parseString(dbCommand.query);
this.dbProcessor.getMany(dbCommand, search, (data, dataErrors, err) => {
if (this.handleErr(response, err)) return;
if (data == null || data.length == 0) {
response.statusCode = HttpStatusCodes.NO_CONTENT;
response.end();
}
else {
response.statusCode = HttpStatusCodes.OK;
response.write("[");
data.forEach((item, index) => {
response.write(item);
if (index < (data.length - 1))
response.write(",");
});
response.end("]");
}
});
}
else {
this.dbProcessor.getSingle(dbCommand, (data, err) => {
if (this.handleErr(response, err)) return;
if (data) {
response.statusCode = HttpStatusCodes.OK;
response.end(data);
}
else {
response.statusCode = HttpStatusCodes.NOT_FOUND;
response.end();
}
});
}
}
private processPostAction(dbCommand: DbCommand, request: Http.IncomingMessage, response: Http.ServerResponse) {
this.readAndParseRequestBody(request, (entity, err) => {
if (this.handleErr(response, err)) return;
if (entity == null) {
this.badRequest(response, "Could not parse payload as JSON.");
return;
}
this.dbProcessor.saveSingle(dbCommand, entity, (data, err) => {
if (this.handleErr(response, err)) return;
response.statusCode = HttpStatusCodes.CREATED;
response.setHeader("Location", Util.format("/%s/%s/%s", dbCommand.dbName, dbCommand.entityName, entity.id));
response.end(data);
});
});
}
private processPutAction(dbCommand: DbCommand, request: Http.IncomingMessage, response: Http.ServerResponse) {
this.readAndParseRequestBody(request, (entity, err) => {
if (this.handleErr(response, err)) return;
if (entity == null) {
this.badRequest(response, "Could not parse payload as JSON.");
return;
}
// TODO Add config option to optionally perform/enforce this.
if (entity.id != null && entity.id != dbCommand.entityId) {
this.badRequest(response, "The entity identifier in the URL must match that of the entity in the request body.");
return;
}
this.dbProcessor.saveSingle(dbCommand, entity, (data, err) => {
if (this.handleErr(response, err)) return;
response.statusCode = HttpStatusCodes.OK;
response.end(data);
});
});
}
private processDeleteAction(dbCommand: DbCommand, request: Http.IncomingMessage, response: Http.ServerResponse) {
this.dbProcessor.deleteSingle(dbCommand, (err) => {
if (this.handleErr(response, err)) return;
response.statusCode = HttpStatusCodes.OK;
response.end();
});
}
private readRequestBody(request: Http.IncomingMessage, callback: (rawData: string) => any) {
var rawData = "";
request.on("data", (chunk: any) => {
rawData += chunk;
});
request.on("end", () => {
callback(rawData);
});
}
private readAndParseRequestBody(request: Http.IncomingMessage, callback: (data: any, err?: any) => any) {
this.readRequestBody(request, (rawData: string) => {
var data: any = null;
try {
data = JSON.parse(rawData);
}
catch (err) {
callback(null, Util.format("Unable to parse request body as JSON. %s", err));
return;
}
callback(data);
});
}
private handleErr(response: Http.ServerResponse, err: any) {
if (err)
this.badRequest(response, err);
}
private badRequest(response: Http.ServerResponse, err: any) {
response.statusCode = HttpStatusCodes.BAD_REQUEST;
response.end(err.toString());
}
}