-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbCommand.ts
67 lines (53 loc) · 2.04 KB
/
DbCommand.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
import * as Http from "http";
import * as Util from "util";
import * as Url from "url";
import * as Path from "path";
import {ArgumentNullError} from "./ArgumentNullError";
export class DbCommand {
private dataPath: string;
public dbName: string;
public entityName: string;
public entityId: string;
public query: any;
constructor(dataPath: string, dbName: string, entityName?: string, entityId?: string, query?: any) {
if (!dataPath) throw new ArgumentNullError("dataPath");
if (!dbName) throw new ArgumentNullError("dbName");
this.dataPath = dataPath;
this.dbName = dbName;
this.entityName = entityName;
this.entityId = entityId;
this.query = query;
}
public getDbRootPath(): string {
return Path.join(this.dataPath, this.dbName)
}
public getEntityRootPath(): string {
return Path.join(this.getDbRootPath(), this.entityName)
}
public getEntityPath(): string {
return Path.join(this.getEntityRootPath(), this.getFilenameForEntity(this.entityId))
}
public getFilenameForEntity(id: string) {
return Util.format("%s.json", id);
}
public hasEntityName(): boolean {
return (this.entityName != null);
}
public hasEntityId(): boolean {
return (this.hasEntityName() && this.entityId != null);
}
public forEntityId(id: string): DbCommand {
return new DbCommand(this.dataPath, this.dbName, this.entityName, id, this.query);
}
public static parseRequest(dataPath: string, request: Http.IncomingMessage): DbCommand {
var url = Url.parse(request.url);
var match = /^\/?([^/?]+)(?:\/([^/?]+))?(?:\/([^/?]+))?/.exec(url.path);
if (match != null) {
var dbName = match[1];
var entityName = match[2];
var entityId = match[3];
var dbCommand = new DbCommand(dataPath, dbName, entityName, entityId, url.query);
return dbCommand;
}
}
}