-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathKeys.ts
52 lines (43 loc) · 1.52 KB
/
Keys.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
import { createHmac } from "crypto";
import ApiCall from "./ApiCall";
import { KeyCreateSchema, KeySchema } from "./Key";
import { SearchParams } from "./Documents";
import { normalizeArrayableParams } from "./Utils";
const RESOURCEPATH = "/keys";
export interface KeysRetrieveSchema {
keys: KeySchema[];
}
export interface GenerateScopedSearchKeyParams extends Partial<SearchParams> {
expires_at?: number;
cache_ttl?: number;
limit_multi_searches?: number;
}
export default class Keys {
constructor(private apiCall: ApiCall) {
this.apiCall = apiCall;
}
async create(params: KeyCreateSchema): Promise<KeySchema> {
return this.apiCall.post<KeySchema>(Keys.RESOURCEPATH, params);
}
async retrieve(): Promise<KeysRetrieveSchema> {
return this.apiCall.get<KeysRetrieveSchema>(RESOURCEPATH);
}
generateScopedSearchKey(
searchKey: string,
parameters: GenerateScopedSearchKeyParams
): string {
// Note: only a key generated with the `documents:search` action will be
// accepted by the server, when usined with the search endpoint.
const normalizedParams = normalizeArrayableParams(parameters);
const paramsJSON = JSON.stringify(normalizedParams);
const digest = Buffer.from(
createHmac("sha256", searchKey).update(paramsJSON).digest("base64")
);
const keyPrefix = searchKey.substr(0, 4);
const rawScopedKey = `${digest}${keyPrefix}${paramsJSON}`;
return Buffer.from(rawScopedKey).toString("base64");
}
static get RESOURCEPATH() {
return RESOURCEPATH;
}
}