-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudflare-kv.service.ts
More file actions
68 lines (58 loc) · 1.9 KB
/
Copy pathcloudflare-kv.service.ts
File metadata and controls
68 lines (58 loc) · 1.9 KB
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
import { Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService } from './../common/configs/config.service';
import { LoggerService } from '../common/logger/logger.service';
import { KvNamespaces } from './models/kv-namespaces.enum';
@Injectable()
export class CloudflareKvService implements OnModuleInit {
private edgeKvUrl: string;
private authorizationToken: string;
constructor(
private readonly configService: ConfigService,
private readonly logger: LoggerService
) {}
onModuleInit() {
this.edgeKvUrl = this.configService.get('EDGE_KV_URL');
this.authorizationToken = this.configService.get('EDGE_KV_AUTHORIZATION_TOKEN');
}
private getErrorMessage(e: unknown): string {
if (e instanceof Error) return e.message;
if (typeof e === 'string') return e;
try {
return JSON.stringify(e);
} catch {
return 'Unknown error';
}
}
async createKeyValueForNamespace(namespace: KvNamespaces, key: string, value?: string | object) {
try {
const requestOptions = {
method: 'POST',
headers: {
authorizationToken: this.authorizationToken,
},
};
const response = await fetch(`${this.edgeKvUrl}/${namespace}/${key}`, requestOptions);
return response;
} catch (e: unknown) {
this.logger.error('Failed to update workers KV', {
errorMessage: this.getErrorMessage(e),
});
}
}
async deleteKeyForNamespace(namespace: KvNamespaces, key: string) {
try {
const requestOptions = {
method: 'DELETE',
headers: {
authorizationToken: this.authorizationToken,
},
};
const response = await fetch(`${this.edgeKvUrl}/${namespace}/${key}`, requestOptions);
return response.json();
} catch (e: unknown) {
this.logger.error('Failed to update workers KV', {
errorMessage: this.getErrorMessage(e),
});
}
}
}