-
Notifications
You must be signed in to change notification settings - Fork 30
/
param.ts
87 lines (72 loc) · 2.57 KB
/
param.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
/**
* @module std/param
*/
import { flatbuffers } from './internal/flatbuffers';
import { __std } from './internal/__std_generated';
import { sendRequest } from './internal/deferred';
import ParamType = __std.ParamType;
function getParameter<T>(type: ParamType, path: string, defaultValue: T): T | undefined {
const builder = new flatbuffers.Builder(512);
const pathOffset = builder.createString(path);
const isObject = type === __std.ParamType.Object;
const defaultValueOffset = isObject
&& defaultValue !== undefined
&& builder.createString(JSON.stringify(defaultValue));
__std.ParamArgs.startParamArgs(builder);
__std.ParamArgs.addPath(builder, pathOffset);
__std.ParamArgs.addType(builder, type);
if (isObject) {
__std.ParamArgs.addDefaultValue(builder, defaultValueOffset);
}
const argsOffset = __std.ParamArgs.endParamArgs(builder);
__std.Message.startMessage(builder);
__std.Message.addArgsType(builder, __std.Args.ParamArgs);
__std.Message.addArgs(builder, argsOffset);
const messageOffset = __std.Message.endMessage(builder);
builder.finish(messageOffset);
const bytes = <ArrayBuffer>sendRequest(builder.asArrayBuffer());
const buf = new flatbuffers.ByteBuffer(new Uint8Array(bytes));
const resp = __std.ParamResponse.getRootAsParamResponse(buf);
switch (resp.retvalType()) {
case __std.ParamRetval.ParamValue: {
// The runtime has returned the parameter value (or null).
const ret = new __std.ParamValue();
resp.retval(ret);
const v = JSON.parse(<string>ret.json());
if (v == null) {
return defaultValue;
}
return v;
}
case __std.ParamRetval.Error: {
// The runtime has returned an error.
const err = new __std.Error();
resp.retval(err);
throw new Error(<string>err.message());
}
default:
throw new Error('Unexpected response to param');
}
}
export function Boolean(path: string, defaultValue?: boolean): boolean | undefined {
return getParameter(__std.ParamType.Boolean, path, defaultValue);
}
export function Number(path: string, defaultValue?: number): number | undefined {
return getParameter(__std.ParamType.Number, path, defaultValue);
}
export function String(path: string, defaultValue?: string): string | undefined {
return getParameter(__std.ParamType.String, path, defaultValue);
}
export function Object(path: string, defaultValue?: object): object | undefined {
return getParameter(__std.ParamType.Object, path, defaultValue);
}
export function all(): object {
return <object>Object('');
}
export const param = {
all,
Boolean,
Number,
String,
Object,
};