@engineers/gcloud-storage 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Dibo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -6,17 +6,19 @@ google cloud storage
6
6
 
7
7
  install the package and it's peer dependencies:
8
8
 
9
+ <!-- todo: peerDependencies.toString() -->
10
+
9
11
  ```
10
12
  npm i @engineers/gcloud-storage
11
13
  ```
12
14
 
13
- you can build this package and any of our packages yourself from [source](https://github.com/eng-dibo/dibo/tree/main/packages)
15
+ you can build this package and any of our packages yourself from [source](https://github.com/its-dibo/dibo/tree/main/packages)
14
16
 
15
17
  ## contributing
16
18
 
17
19
  contributing with us are very welcome.
18
20
 
19
- read our [contributing guide](https://github.com/eng-dibo/dibo/blob/main/CONTRIBUTING.md)
21
+ read our [contributing guide](https://github.com/its-dibo/dibo/blob/main/CONTRIBUTING.md)
20
22
 
21
23
  ## support us
22
24
 
@@ -24,26 +26,60 @@ read our [contributing guide](https://github.com/eng-dibo/dibo/blob/main/CONTRIB
24
26
 
25
27
  - [patreon](https://www.patreon.com/GoogleDev)
26
28
 
29
+ ## apps by `@engineers`
30
+
31
+ - [ngx-cms](https://github.com/its-dibo/dibo/tree/main/projects/ngx-cms)
32
+
33
+ - [social-control](https://github.com/its-dibo/dibo/tree/main/projects/social-control)
34
+
35
+ - [vscode](https://github.com/its-dibo/dibo/tree/main/projects/vscode)
36
+
27
37
  ## useful packages by `@engineers`
28
38
 
29
39
  - check out these useful packages that created by [@engineers organization](https://www.npmjs.com/org/engineers)
30
40
 
31
- - [cache](https://github.com/eng-dibo/dibo/tree/main/packages/cache)
32
- - [databases](https://github.com/eng-dibo/dibo/tree/main/packages/databases)
33
- - [dibo-system](https://github.com/eng-dibo/dibo/tree/main/packages/dibo-system)
34
- - [dom](https://github.com/eng-dibo/dibo/tree/main/packages/dom)
35
- - [express-redirect-middleware](https://github.com/eng-dibo/dibo/tree/main/packages/express-redirect-middleware)
36
- - [firebase-admin](https://github.com/eng-dibo/dibo/tree/main/packages/firebase-admin)
37
- - [gcloud-storage](https://github.com/eng-dibo/dibo/tree/main/packages/gcloud-storage)
38
- - [graphics](https://github.com/eng-dibo/dibo/tree/main/packages/graphics)
39
- - [javascript](https://github.com/eng-dibo/dibo/tree/main/packages/javascript)
40
- - [lazy-load](https://github.com/eng-dibo/dibo/tree/main/packages/lazy-load)
41
- - [mongoose](https://github.com/eng-dibo/dibo/tree/main/packages/mongoose)
42
- - [ngx-content-core](https://github.com/eng-dibo/dibo/tree/main/packages/ngx-content-core)
43
- - [ngx-content-view-mat](https://github.com/eng-dibo/dibo/tree/main/packages/ngx-content-view-mat)
44
- - [ngx-universal-express](https://github.com/eng-dibo/dibo/tree/main/packages/ngx-universal-express)
45
- - [ngx-utils](https://github.com/eng-dibo/dibo/tree/main/packages/ngx-utils)
46
- - [nodejs](https://github.com/eng-dibo/dibo/tree/main/packages/nodejs)
47
- - [rxjs](https://github.com/eng-dibo/dibo/tree/main/packages/rxjs)
48
- - [tmpl](https://github.com/eng-dibo/dibo/tree/main/packages/tmpl)
49
- - [webpack](https://github.com/eng-dibo/dibo/tree/main/packages/webpack)
41
+ - [cache](https://www.npmjs.com/package/@engineers/cache)
42
+
43
+ - [databases](https://www.npmjs.com/package/@engineers/databases)
44
+
45
+ - [dom](https://www.npmjs.com/package/@engineers/dom)
46
+
47
+ - [express](https://www.npmjs.com/package/@engineers/express)
48
+
49
+ - [firebase-admin](https://www.npmjs.com/package/@engineers/firebase-admin)
50
+
51
+ - [gcloud-storage](https://www.npmjs.com/package/@engineers/gcloud-storage)
52
+
53
+ - [geo](https://www.npmjs.com/package/@engineers/geo)
54
+
55
+ - [graphics](https://www.npmjs.com/package/@engineers/graphics)
56
+
57
+ - [hookable](https://www.npmjs.com/package/@engineers/hookable)
58
+
59
+ - [javascript](https://www.npmjs.com/package/@engineers/javascript)
60
+
61
+ - [lazy-load](https://www.npmjs.com/package/@engineers/lazy-load)
62
+
63
+ - [mongoose](https://www.npmjs.com/package/@engineers/mongoose)
64
+
65
+ - [ngx-chat-firebase-mat](https://www.npmjs.com/package/@engineers/ngx-chat-firebase-mat)
66
+
67
+ - [ngx-content-core](https://www.npmjs.com/package/@engineers/ngx-content-core)
68
+
69
+ - [ngx-content-view-mat](https://www.npmjs.com/package/@engineers/ngx-content-view-mat)
70
+
71
+ - [ngx-formly](https://www.npmjs.com/package/@engineers/ngx-formly)
72
+
73
+ - [ngx-universal-express](https://www.npmjs.com/package/@engineers/ngx-universal-express)
74
+
75
+ - [ngx-utils](https://www.npmjs.com/package/@engineers/ngx-utils)
76
+
77
+ - [nodejs](https://www.npmjs.com/package/@engineers/nodejs)
78
+
79
+ - [rxjs](https://www.npmjs.com/package/@engineers/rxjs)
80
+
81
+ - [tmpl](https://www.npmjs.com/package/@engineers/tmpl)
82
+
83
+ - [updater](https://www.npmjs.com/package/@engineers/updater)
84
+
85
+ - [webpack](https://www.npmjs.com/package/@engineers/webpack)
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './src';
2
+ export { default as Storage } from './src';
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./src";
2
+ import { default as default2 } from "./src";
3
+ export {
4
+ default2 as Storage
5
+ };
package/nx.json ADDED
@@ -0,0 +1,177 @@
1
+ {
2
+ "$schema": "./node_modules/nx/schemas/nx-schema.json",
3
+ "targetDefaults": {
4
+ "build": {
5
+ "executor": "@engineers/nx-manager:universal-builder",
6
+ "dependsOn": ["typecheck", "prebuild", "^build"],
7
+ "cache": true,
8
+ "inputs": ["default", "^default"],
9
+ "outputs": ["{projectRoot}/dist"],
10
+ "options": {
11
+ "forceRnDefaultPostBuild": true
12
+ }
13
+ },
14
+ "serve": {
15
+ "executor": "nx:run-commands",
16
+ "dependsOn": ["build", "preserve"],
17
+ "continuous": true,
18
+ "options": {
19
+ "cwd": "{projectRoot}",
20
+ "command": "NODE_ENV=development pnpm tsx --env-file-if-exists=.env --env-file-if-exists=.env.local dist/main.js"
21
+ },
22
+ "configurations": {
23
+ "production": {
24
+ "command": "NODE_ENV=production pnpm tsx --env-file-if-exists=.env --env-file-if-exists=.env.local --env-file-if-exists=.env.production --env-file-if-exists=.env.production.local dist/main.js"
25
+ }
26
+ }
27
+ },
28
+ "nx-release-publish": {
29
+ "options": {
30
+ "packageRoot": "{projectRoot}/dist"
31
+ }
32
+ },
33
+ "semantic-release": {
34
+ "executor": "nx:run-commands",
35
+ "dependsOn": ["build", "prerelease"],
36
+ "options": {
37
+ "cwd": "{projectRoot}",
38
+ "command": "pnpm tsx node_modules/semantic-release/bin/semantic-release.js"
39
+ },
40
+ "configurations": {
41
+ "local": {
42
+ "command": "DOTENV_CONFIG_PATH=../../.env pnpm run release --no-ci"
43
+ },
44
+ "dry": {
45
+ "command": "DOTENV_CONFIG_PATH=../../.env pnpm run release --no-ci --dry-run"
46
+ }
47
+ }
48
+ },
49
+ "test": {
50
+ "inputs": ["test"],
51
+ "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
52
+ "dependsOn": ["^build", "pretest"],
53
+ "configurations": {
54
+ "unit": {
55
+ "args": [
56
+ "--testPathIgnorePatterns '.*\\.e2e\\.spec\\.ts$'",
57
+ "--testPathIgnorePatterns '/.*-e2e/'",
58
+ "--testPathIgnorePatterns '/.*-e2e/'"
59
+ ]
60
+ },
61
+ "e2e": {
62
+ "args": [
63
+ "--testMatch '**/*-e2e/**/*.{spec,test}.[mc]?[jt]s?(x)'",
64
+ "--testMatch '**/e2e/**/*.{spec,test}.[mc]?[jt]s?(x)'",
65
+ "--testMatch '**/*.e2e.(spec|test).?([mc])[jt]s?(x)'"
66
+ ]
67
+ }
68
+ }
69
+ },
70
+ "@angular/build:application": {
71
+ "cache": true,
72
+ "dependsOn": ["prebuild", "^build"],
73
+ "inputs": ["default", "^default"]
74
+ },
75
+ "@nx/angular:package": {
76
+ "cache": true,
77
+ "dependsOn": ["^build"],
78
+ "inputs": ["default", "^default"],
79
+ "outputs": ["{projectRoot}/dist"],
80
+ "options": {
81
+ "project": "{projectRoot}/ng-package.json",
82
+ "tsConfig": "{projectRoot}/tsconfig.lib.json"
83
+ }
84
+ },
85
+ "@nx/js:tsc": {
86
+ "cache": true,
87
+ "dependsOn": ["^build"],
88
+ "inputs": ["default", "^default"]
89
+ }
90
+ },
91
+ "namedInputs": {
92
+ "default": [
93
+ "{projectRoot}/src/**/*",
94
+ "!{projectRoot}/**/*.(spec|test)(.e2e)?.[tj]sx?",
95
+ "!{projectRoot}/**/e2e/**/*",
96
+ "{projectRoot}/.env(.*)?",
97
+ "{workspaceRoot}/tasks/(post-)?build.ts",
98
+ "{projectRoot}/(project|package|tsconfig)(.+)?.json",
99
+ "{workspaceRoot}/tsconfig.base.json",
100
+ {
101
+ "runtime": "node --version"
102
+ },
103
+ {
104
+ "env": "NODE_ENV"
105
+ }
106
+ ],
107
+ "test": [
108
+ "default",
109
+ "{projectRoot}/tsconfig.spec.json",
110
+ "{projectRoot}/jest.config.[jt]s",
111
+ "{workspaceRoot}/jest.config.[jt]s",
112
+ "{projectRoot}/**/*.(spec|test)(.e2e)?.[jt]sx?",
113
+ "{projectRoot}/**/e2e/**/*.[jt]sx?",
114
+ {
115
+ "externalDependencies": ["jest"]
116
+ }
117
+ ]
118
+ },
119
+ "plugins": [
120
+ {
121
+ "plugin": "@nx/js/typescript",
122
+ "options": {
123
+ "typecheck": {
124
+ "targetName": "typecheck"
125
+ },
126
+ "build": false
127
+ }
128
+ },
129
+ {
130
+ "plugin": "@nx/jest/plugin",
131
+ "options": {
132
+ "targetName": "test",
133
+ "ciTargetName": "test-ci"
134
+ }
135
+ }
136
+ ],
137
+ "tasksRunnerOptions": {
138
+ "default": {
139
+ "options": {
140
+ "useDaemonProcess": false
141
+ }
142
+ }
143
+ },
144
+ "generators": {
145
+ "@nx/angular:library": {
146
+ "linter": "eslint",
147
+ "unitTestRunner": "jest"
148
+ },
149
+ "@nx/angular:component": {
150
+ "style": "scss"
151
+ }
152
+ },
153
+ "release": {
154
+ "projectsRelationship": "independent",
155
+ "version": {
156
+ "conventionalCommits": true,
157
+ "updateDependents": "always",
158
+ "preVersionCommand": "pnpm nx run-many -t build",
159
+ "manifestRootsToUpdate": [
160
+ "{projectRoot}",
161
+ {
162
+ "path": "{projectRoot}/dist",
163
+ "preserveLocalDependencyProtocols": false
164
+ }
165
+ ]
166
+ },
167
+ "releaseTag": {
168
+ "pattern": "{projectName}@{version}"
169
+ },
170
+ "changelog": {
171
+ "projectChangelogs": true
172
+ }
173
+ },
174
+ "sync": {
175
+ "applyChanges": false
176
+ }
177
+ }
package/package.json CHANGED
@@ -1,25 +1,57 @@
1
1
  {
2
2
  "name": "@engineers/gcloud-storage",
3
- "version": "1.0.0",
4
- "files": [
5
- "dist"
6
- ],
3
+ "version": "2.0.0",
4
+ "type": "module",
7
5
  "description": "google cloud storage",
8
6
  "private": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
9
10
  "dependencies": {
10
- "@google-cloud/storage": "^5.19.0"
11
+ "@google-cloud/storage": "^7.18.0"
12
+ },
13
+ "nx": {
14
+ "projectType": "library",
15
+ "targets": {
16
+ "build": {},
17
+ "semantic-release": {}
18
+ }
19
+ },
20
+ "imports": {
21
+ "#*": "./src/*.js"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./index.d.js",
26
+ "default": "./index.js"
27
+ },
28
+ "./package.json": {
29
+ "default": "./package.json"
30
+ },
31
+ "./*": "./src/*"
32
+ },
33
+ "devDependencies": {
34
+ "@engineers/javascript": "2.0.2",
35
+ "@engineers/nodejs": "2.0.1",
36
+ "semantic-release": "^25.0.2",
37
+ "semantic-release-monorepo": "^8.0.2",
38
+ "tsx": "^4.21.0"
39
+ },
40
+ "engines": {
41
+ "node": "^18.19.1 || ^20.11.1 || >=22.0.0"
11
42
  },
12
43
  "repository": {
13
44
  "type": "git",
14
- "url": "https://github.com/eng-dibo/dibo.git"
45
+ "url": "https://github.com/its-dibo/dibo.git"
15
46
  },
16
- "homepage": "https://github.com/eng-dibo/dibo#readme",
47
+ "author": "Sherif Eldeeb <sh.eldeeb.2010+github@gmail.com> (https://github.com/its-dibo)",
48
+ "homepage": "https://github.com/its-dibo/dibo#readme",
17
49
  "bugs": {
18
- "url": "https://github.com/eng-dibo/dibo/issues",
50
+ "url": "https://github.com/its-dibo/dibo/issues",
19
51
  "email": "sh.eldeeb.2010+github@gmail.com"
20
52
  },
21
53
  "license": "MIT",
22
- "author": "Sherif Eldeeb <sh.eldeeb.2010+github@gmail.com> (https://github.com/eng-dibo)",
54
+ "contributors": [],
23
55
  "funding": [
24
56
  {
25
57
  "type": "paypal",
@@ -30,14 +62,5 @@
30
62
  "url": "https://www.patreon.com/GoogleDev"
31
63
  }
32
64
  ],
33
- "scripts": {
34
- "build": "webpack",
35
- "_publish": "npm run build && npm publish --access=public",
36
- "release": "semantic-release",
37
- "release:local": "semantic-release --no-ci"
38
- },
39
- "devDependencies": {
40
- "semantic-release": "^19.0.2",
41
- "semantic-release-monorepo": "^7.0.5"
42
- }
43
- }
65
+ "scripts": {}
66
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { Bucket, type CreateBucketRequest, File, type SaveOptions, Storage, type UploadResponse, type StorageOptions as _StorageOptions } from '@google-cloud/storage';
2
+ import { type PathLike } from 'node:fs';
3
+ export interface StorageOptions extends _StorageOptions {
4
+ bucket: string;
5
+ rootDir?: string;
6
+ }
7
+ export interface UploadOptions {
8
+ destination: string;
9
+ }
10
+ export interface DownloadOptions {
11
+ destination?: string;
12
+ encoding?: BufferEncoding | null;
13
+ }
14
+ export interface DeleteOptions {
15
+ ignoreNotFound?: boolean;
16
+ }
17
+ export interface ExistsOptions {
18
+ }
19
+ export interface CreateBucketMeta extends CreateBucketRequest {
20
+ labels?: {
21
+ [key: string]: string;
22
+ };
23
+ }
24
+ export default class {
25
+ storage: Storage;
26
+ bucket: Bucket;
27
+ private baseDir;
28
+ constructor(options: StorageOptions);
29
+ upload(path: PathLike, options?: UploadOptions | string): Promise<UploadResponse | void>;
30
+ download(file: PathLike | File, options?: DownloadOptions | string): Promise<Buffer | string | Array<any> | {
31
+ [key: string]: any;
32
+ } | void>;
33
+ downloadAll(destination: PathLike, directory?: PathLike, filter?: RegExp | ((file: string) => boolean), options?: {
34
+ start?: number;
35
+ end?: number;
36
+ }): Promise<{
37
+ [key: string]: boolean;
38
+ }>;
39
+ write(path: PathLike, content?: any, options?: SaveOptions): Promise<any>;
40
+ read(file: PathLike | File, options?: DownloadOptions | string): Promise<string | void | any[] | Buffer<ArrayBufferLike> | {
41
+ [key: string]: any;
42
+ }>;
43
+ delete(path: PathLike, options?: DeleteOptions): Promise<any>;
44
+ exists(path: PathLike, options?: ExistsOptions): Promise<boolean>;
45
+ create(metaData?: CreateBucketMeta): Promise<import("@google-cloud/storage").CreateBucketResponse>;
46
+ }
package/src/index.js ADDED
@@ -0,0 +1,200 @@
1
+ import {
2
+ Storage
3
+ } from "@google-cloud/storage";
4
+ import { mkdirSync } from "node:fs";
5
+ import { dirname, resolve } from "node:path";
6
+ import { cleanJson, objectType } from "@engineers/javascript";
7
+ import { URL } from "node:url";
8
+ class src_default {
9
+ storage;
10
+ bucket;
11
+ baseDir;
12
+ /**
13
+ * creates a new bucket
14
+ *
15
+ * @function constructor
16
+ * @param options
17
+ * @param bucket
18
+ */
19
+ // todo: if(bucket instanceof admin.Bucket)this.bucket=bucket
20
+ // constructor();
21
+ constructor(options) {
22
+ let opts = { ...options };
23
+ if (!opts.keyFile && !opts.keyFilename && !opts.credentials && process.env.gcloud_service_account_storage) {
24
+ opts.credentials = JSON.parse(process.env.gcloud_service_account_storage);
25
+ }
26
+ this.storage = new Storage(opts);
27
+ if (opts.bucket.includes("/")) {
28
+ let parts = opts.bucket.split("/");
29
+ opts.bucket = parts.shift();
30
+ this.baseDir = parts.join("/") + opts.rootDir ? "/" + opts.rootDir : "";
31
+ }
32
+ this.bucket = this.storage.bucket(opts.bucket);
33
+ }
34
+ /**
35
+ * uploads a file to the current bucket
36
+ *
37
+ * @function upload
38
+ * @param file file path
39
+ * @param path
40
+ * @param options UploadOptions object or destination path as string
41
+ * @returns Promise<UploadResponse>; //UploadResponse=[File, API request]
42
+ */
43
+ // todo: upload / download a folder
44
+ upload(path, options) {
45
+ let opts = {
46
+ ...typeof options === "string" ? { destination: options } : options || {}
47
+ };
48
+ if (this.baseDir && opts?.destination) {
49
+ opts.destination = `${this.baseDir}/${opts.destination}`;
50
+ }
51
+ return this.bucket.upload(path.toString(), opts);
52
+ }
53
+ /**
54
+ * downloads a file
55
+ *
56
+ * @function download
57
+ * @param file file path
58
+ * @param options DownloadOptions object or destination as string
59
+ * @returns Promise that resolves to:
60
+ * - void: if options.destination used
61
+ * - Buffer: if options.encoding is undefined
62
+ * - Array or plain object: if the file is json
63
+ * - string: otherwise
64
+ */
65
+ // todo: if(!options.destination)return th content as Promise<Buffer | ...>
66
+ // otherwise write the content into a local destination and return boolean
67
+ download(file, options) {
68
+ if (typeof file === "string" || // note: TS doesn't narrow down the type `Buffer<ArrayBufferLike>`
69
+ // so, it'll still see the type of file as `File | Buffer<ArrayBufferLike>`
70
+ // you may need to explicitly use `<File>file`
71
+ file instanceof Buffer || file instanceof URL) {
72
+ file = this.bucket.file(
73
+ this.baseDir ? `${this.baseDir}/${file.toString()}` : file.toString()
74
+ );
75
+ }
76
+ let opts = Object.assign(
77
+ { encoding: null },
78
+ typeof options === "string" ? { destination: options } : options || {}
79
+ );
80
+ if (opts.destination) {
81
+ mkdirSync(dirname(opts.destination), { recursive: true });
82
+ }
83
+ return file.download({ ...opts }).then((result) => {
84
+ if (opts.destination) {
85
+ return;
86
+ }
87
+ let data = result[0];
88
+ if (opts.encoding === void 0) {
89
+ return data;
90
+ }
91
+ let dataString = data.toString();
92
+ try {
93
+ return file.name.slice(-5) === ".json" ? JSON.parse(cleanJson(dataString)) : dataString;
94
+ } catch {
95
+ return dataString;
96
+ }
97
+ });
98
+ }
99
+ /**
100
+ * download all files from a directory that match the provided filter
101
+ *
102
+ * @param destination the local path to download the files to
103
+ * @param directory the directory to be downloaded
104
+ * @param filter a pattern or function to filter the files to be downloaded
105
+ * @param options
106
+ * @param options.start download all files starting from the specified one (paginating behavior) (default is the first file)
107
+ * @param options.end download all files until the specified file (default is the last file)
108
+ * @returns a map of {file: result}
109
+ */
110
+ downloadAll(destination, directory, filter, options = {}) {
111
+ options = Object.assign({ start: 0, end: void 0 }, options || {});
112
+ let results = {};
113
+ if (!filter) {
114
+ filter = (_file) => true;
115
+ } else if (filter instanceof RegExp) {
116
+ filter = (file) => filter.test(file);
117
+ }
118
+ if (this.baseDir) {
119
+ directory = `${this.baseDir}/${directory}`;
120
+ }
121
+ return this.bucket.getFiles({ prefix: directory?.toString() }).then((files) => files[0].filter((file) => filter(file.name))).then(
122
+ (files) => Promise.all(
123
+ files.slice(options.start, options.end).map(
124
+ (file) => this.download(file, {
125
+ destination: resolve(`${destination.toString()}/${file.name}`)
126
+ }).then((_result) => {
127
+ results[file.name] = true;
128
+ }).catch((_error) => {
129
+ results[file.name] = false;
130
+ })
131
+ )
132
+ ).then(() => results)
133
+ );
134
+ }
135
+ /**
136
+ * writes a content to a file in the bucket
137
+ *
138
+ * @param path bucket path
139
+ * @param content the content to be written. if no content provided, an empty file is created
140
+ * @param options
141
+ * @returns the original content
142
+ */
143
+ write(path, content = "", options) {
144
+ if (this.baseDir) {
145
+ path = `${this.baseDir}/${path}`;
146
+ }
147
+ return this.bucket.file(path.toString()).save(
148
+ ["array", "object"].includes(objectType(content)) ? JSON.stringify(content) : content,
149
+ options
150
+ ).then(() => content);
151
+ }
152
+ /** an alias to download() to be compatible with node:fs functions */
153
+ read(file, options) {
154
+ return this.download(file, options);
155
+ }
156
+ // https://stackoverflow.com/a/64539948/12577650
157
+ delete(path, options) {
158
+ if (this.baseDir) {
159
+ path = `${this.baseDir}/${path}`;
160
+ }
161
+ return this.bucket.file(path.toString()).delete(options);
162
+ }
163
+ /**
164
+ * check if a file exists in the bucket
165
+ * this method works with files only, not folders
166
+ * folders doesn't actually exist
167
+ * https://cloud.google.com/storage/docs/folders
168
+ *
169
+ * @param path file path
170
+ * @param options
171
+ * @returns boolean
172
+ */
173
+ exists(path, options) {
174
+ if (this.baseDir) {
175
+ path = `/${this.baseDir}/${path}`;
176
+ }
177
+ return this.bucket.file(path.toString()).exists(options).then((result) => result[0]);
178
+ }
179
+ /**
180
+ * create a new bucket, and optionally add labels to it
181
+ * add the desired labels as key-value pairs to metaData.labels
182
+ * https://cloud.google.com/storage/docs/using-bucket-labels#storage-modify-bucket-label-nodejs
183
+ *
184
+ * @param metaData
185
+ * @returns
186
+ */
187
+ create(metaData) {
188
+ let bucketName = this.bucket.name;
189
+ let { labels, ...meta } = metaData || {};
190
+ return this.storage.createBucket(bucketName, meta).then((result) => {
191
+ this.bucket.name = bucketName;
192
+ return labels ? this.bucket.setLabels(labels).then(() => result) : result;
193
+ });
194
+ }
195
+ // todo: read(file:string):Buffer
196
+ // todo: delete folder
197
+ }
198
+ export {
199
+ src_default as default
200
+ };
@@ -0,0 +1,72 @@
1
+ import { afterAll, expect, test } from "@jest/globals";
2
+ import Storage from "./index";
3
+ import { read, remove, resolve, writeSync } from "@engineers/nodejs";
4
+ import { existsSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ const __dirname = dirname(fileURLToPath(import.meta.url));
8
+ let serviceAccount = resolve(__dirname, "./gcloud-service-account!!.json");
9
+ if (existsSync(serviceAccount)) {
10
+ let bucket = `dibo-testing/test!!/gcloud-storage`;
11
+ let storage = new Storage({ bucket, keyFilename: serviceAccount });
12
+ writeSync(__dirname + "/test~~/file.json", { ok: 1 });
13
+ afterAll(() => {
14
+ return Promise.all(
15
+ ["file.json"].map((file) => storage.delete(`${file}`))
16
+ ).then(() => remove(__dirname + "/test~~"));
17
+ });
18
+ test("upload", () => {
19
+ return storage.upload(__dirname + "/test~~/file.json", `file.json`).then((result) => {
20
+ let metadata = result[1];
21
+ expect(metadata.kind).toEqual("storage#object");
22
+ expect(metadata.name).toEqual(`test!!/gcloud-storage/file.json`);
23
+ expect(metadata.size).toEqual(8);
24
+ });
25
+ });
26
+ test("write", () => {
27
+ return expect(storage.write(`note.txt`, "ok")).resolves.not.toThrow();
28
+ });
29
+ test("download to a destination", () => {
30
+ let destination = __dirname + "/test~~/file.json";
31
+ return expect(
32
+ storage.download(`file.json`, destination)
33
+ ).resolves.not.toThrow();
34
+ });
35
+ test("download as Buffer", () => {
36
+ return storage.download(`file.json`).then((result) => {
37
+ expect(result).toMatchObject({ ok: 1 });
38
+ });
39
+ });
40
+ test("download non-existing file", () => {
41
+ return expect(storage.download(`non-existing.txt`)).rejects.toThrow(
42
+ "No such object"
43
+ );
44
+ });
45
+ test("download to a non-existing directory", () => {
46
+ let destination = __dirname + "/test~~/non-existing/file.json";
47
+ return storage.download(`file.json`, destination).then(() => read(destination)).then((result) => {
48
+ expect(result).toMatchObject({ ok: 1 });
49
+ });
50
+ return expect(
51
+ storage.download(`file.json`, destination)
52
+ ).resolves.not.toThrow();
53
+ });
54
+ test("delete", () => {
55
+ return storage.delete(`note.txt`).then((result) => {
56
+ expect(result).toBeTruthy();
57
+ });
58
+ });
59
+ test("delete non-existing file", () => {
60
+ return expect(storage.delete(`none-existing.txt`)).rejects.toThrow(
61
+ "No such object"
62
+ );
63
+ });
64
+ } else {
65
+ console.warn(
66
+ `testing for gcloud-storage skipped because the service account file does'nt exist
67
+ to run the test create "gcloud-service-account!!.json" contains your own service account
68
+ note that files that end with "!!" or "~~" don't be committed to the remote repository for security`
69
+ );
70
+ test("skip", () => {
71
+ });
72
+ }