-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathget-value.ts
88 lines (68 loc) · 2.5 KB
/
get-value.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
import { Args, Flags } from '@oclif/core';
import { ApifyCommand } from '../../lib/apify_command.js';
import { tryToGetKeyValueStore } from '../../lib/commands/storages.js';
import { error, simpleLog } from '../../lib/outputs.js';
import { getLoggedClientOrThrow } from '../../lib/utils.js';
export class KeyValueStoresGetValueCommand extends ApifyCommand<typeof KeyValueStoresGetValueCommand> {
static override description =
'Retrieves stored value for specified key. Use --only-content-type to check MIME type.';
static override hiddenAliases = ['kvs:get-value'];
static override flags = {
'only-content-type': Flags.boolean({
description: 'Only return the content type of the specified key',
default: false,
}),
};
static override args = {
keyValueStoreId: Args.string({
description: 'The key-value store ID to get the value from.',
required: true,
}),
itemKey: Args.string({
description: 'The key of the item in the key-value store.',
required: true,
}),
};
async run() {
const { onlyContentType } = this.flags;
const { keyValueStoreId, itemKey } = this.args;
const apifyClient = await getLoggedClientOrThrow();
const maybeStore = await tryToGetKeyValueStore(apifyClient, keyValueStoreId);
if (!maybeStore) {
error({ message: `Key-value store with ID "${keyValueStoreId}" not found.` });
return;
}
const { keyValueStoreClient: storeClient } = maybeStore;
const itemRecord = await storeClient.getRecord(itemKey, { stream: true });
if (!itemRecord) {
error({ message: `Item with key "${itemKey}" not found in the key-value store.` });
return;
}
// Print out the content-type on stderr (default to octet-stream for unknown content types)
simpleLog({ message: itemRecord.contentType ?? 'application/octet-stream' });
if (onlyContentType) {
// Close the stream as otherwise the process hangs
itemRecord.value.destroy();
return;
}
// Try to pretty-print JSON
if (itemRecord.contentType?.includes('application/json')) {
const { value: stream } = itemRecord;
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
const concatenated = Buffer.concat(chunks).toString();
try {
const parsed = JSON.parse(concatenated);
simpleLog({ message: JSON.stringify(parsed, null, 2), stdout: true });
} catch {
// Print out as is directly to stdout
simpleLog({ message: concatenated, stdout: true });
}
return;
}
// pipe the output to stdout
itemRecord.value.pipe(process.stdout);
}
}