-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.ts
93 lines (83 loc) · 2.23 KB
/
misc.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
import { V2Client } from "clarifai-nodejs-grpc/proto/clarifai/api/service_grpc_pb";
import { UserError } from "../errors";
import { GrpcWithCallback, AuthConfig } from "./types";
import { grpc } from "clarifai-nodejs-grpc";
/**
* Get a value from a dictionary or an environment variable.
*/
export function getFromDictOrEnv(
key: string,
envKey: string,
data: { [key: string]: string },
): string {
if (data?.[key]) {
return data[key];
} else {
return getFromEnv(key, envKey);
}
}
/**
* Get a value from an environment variable.
*/
function getFromEnv(key: string, envKey: string): string {
if (process.env?.[envKey]) {
return process.env[envKey]!;
} else {
throw new UserError(
`Did not find \`${key}\`, please add an environment variable \`${envKey}\` which contains it, or pass \`${key}\` as a named parameter.`,
);
}
}
export function promisifyGrpcCall<TRequest, TResponse>(
func: GrpcWithCallback<TRequest, TResponse>,
client: V2Client,
): (
request: TRequest,
metadata: grpc.Metadata,
options: Partial<grpc.CallOptions>,
) => Promise<TResponse> {
return (
request: TRequest,
metadata: grpc.Metadata,
options: Partial<grpc.CallOptions>,
): Promise<TResponse> => {
return new Promise((resolve, reject) => {
func.bind(client)(request, metadata, options, (error, response) => {
if (error) {
return reject(error);
}
resolve(response);
});
});
};
}
export function mergeObjects(obj1: AuthConfig, obj2: AuthConfig): AuthConfig {
const result = { ...obj1 };
type KnownKey = keyof AuthConfig;
Object.entries(obj2).forEach(([key, value]) => {
if (value) {
result[key as KnownKey] = value;
}
});
return result;
}
export class BackoffIterator {
private count: number;
constructor({ count } = { count: 0 }) {
this.count = count;
}
[Symbol.iterator]() {
return this;
}
next(): IteratorResult<number> {
if (this.count < 1) {
this.count += 1;
return { value: 0.1, done: false };
} else if (this.count < 7) {
this.count += 1;
return { value: 0.01 * Math.pow(2, this.count + 4), done: false };
} else {
return { value: 0.01 * Math.pow(2, 10), done: false };
}
}
}