forked from max-mapper/google-cloud-storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
98 lines (91 loc) · 2.53 KB
/
index.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
94
95
96
97
98
import { Storage, Bucket } from "@google-cloud/storage";
import { duplexify } from "@justinbeckwith/duplexify";
import {
AbstractBlobStore,
BlobKey,
CreateCallback,
ExistsCallback,
RemoveCallback
} from "abstract-blob-store";
interface CloudStorageBlobOptions {
bucket: string;
keyFilename?: string;
credentials?: {
[key: string]: string;
client_email: string;
private_key: string;
};
}
const KeyError = new Error("Must specify a key");
interface options {
[name: string]: string;
key: string;
}
const getOpts = (opts: BlobKey): options =>
typeof opts === "string"
? { key: opts }
: !opts.key && opts.name
? { key: opts.name }
: opts;
export class CloudStorageBlob implements AbstractBlobStore {
bucket: Bucket;
storage: Storage;
constructor(opts: CloudStorageBlobOptions) {
const { bucket, keyFilename, credentials } = opts;
if (!bucket) {
throw new Error("Must specify bucket");
} else if (!credentials && !keyFilename) {
throw new Error("Must specifiy credentials or keyFilename");
}
this.storage = credentials
? new Storage({ credentials })
: new Storage({ keyFilename });
this.bucket = this.storage.bucket(bucket);
}
createWriteStream(
opts: BlobKey,
callback: CreateCallback
): NodeJS.WriteStream {
const { key } = getOpts(opts);
if (!key) {
throw KeyError;
}
return this.bucket
.file(key)
.createWriteStream()
.on("error", callback)
.on("finish", () => callback(null, { key })) as NodeJS.WriteStream;
}
createReadStream(opts: BlobKey): NodeJS.ReadStream {
const { key } = getOpts(opts);
if (!key) {
throw KeyError;
}
const proxy = duplexify();
proxy.setWritable(null);
this.bucket.file(key).get((err, file) => {
if (err) {
proxy.destroy(err);
} else {
proxy.setReadable(file.createReadStream());
}
});
return (proxy as unknown) as NodeJS.ReadStream;
}
exists(opts: BlobKey, callback: ExistsCallback): void {
const { key } = getOpts(opts);
if (!key) {
return callback(KeyError, false);
}
this.bucket.file(key).exists(callback);
}
remove(opts: BlobKey, callback: RemoveCallback): void {
const { key } = getOpts(opts);
if (!key) {
return callback(KeyError);
}
this.bucket.file(key).delete(callback);
}
}
export const gcs = (opts: CloudStorageBlobOptions) =>
new CloudStorageBlob(opts);