Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
47cf2cc2cb | |||
ef20e15d20 | |||
39a4bd6ab7 | |||
c2a30654c5 | |||
8085033de4 | |||
75dd1d43a9 | |||
8ba7cdc873 | |||
ed8db4536b | |||
96e3eadb31 | |||
e9426b9cc9 | |||
9801e15c32 | |||
cbfdd8e123 | |||
138c38ee30 | |||
a1e449cf94 | |||
aa9a2e9220 | |||
154854dc21 | |||
8e9041fbbf | |||
16a82ac50a |
50
changelog.md
50
changelog.md
@ -1,5 +1,55 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2024-12-02 - 3.3.7 - fix(package)
|
||||||
|
Update author field in package.json
|
||||||
|
|
||||||
|
- Corrected the author field from 'Lossless GmbH' to 'Task Venture Capital GmbH' in the package.json file.
|
||||||
|
|
||||||
|
## 2024-12-02 - 3.3.6 - fix(package)
|
||||||
|
Fix license field in package.json to reflect MIT licensing
|
||||||
|
|
||||||
|
|
||||||
|
## 2024-11-25 - 3.3.5 - fix(test)
|
||||||
|
Refactor trash test to improve metadata validation
|
||||||
|
|
||||||
|
- Added new checks in trash tests to ensure metadata files are correctly moved to trash.
|
||||||
|
- Validated the presence and integrity of metadata within trashed files.
|
||||||
|
|
||||||
|
## 2024-11-25 - 3.3.4 - fix(core)
|
||||||
|
Minor refactoring and cleanup of TypeScript source files for improved readability and maintainability.
|
||||||
|
|
||||||
|
|
||||||
|
## 2024-11-24 - 3.3.3 - fix(documentation)
|
||||||
|
Improved documentation accuracy and consistency
|
||||||
|
|
||||||
|
- Updated the project description to reflect the cloud-agnostic nature and advanced capabilities
|
||||||
|
- Enhanced the README with detailed explanations and code examples for advanced features like trash management
|
||||||
|
- Clarified the handling and importance of metadata using the MetaData utility
|
||||||
|
|
||||||
|
## 2024-11-24 - 3.3.2 - fix(documentation)
|
||||||
|
Updated keywords and description for clarity and consistency.
|
||||||
|
|
||||||
|
- Modified keywords and description in package.json and npmextra.json.
|
||||||
|
- Enhanced readme.md file structure and examples
|
||||||
|
|
||||||
|
## 2024-11-24 - 3.3.1 - fix(File)
|
||||||
|
Fixed issue with file restore metadata operations.
|
||||||
|
|
||||||
|
- Corrected the order of operations in the file restore function to ensure custom metadata is appropriately deleted after moving the file.
|
||||||
|
|
||||||
|
## 2024-11-24 - 3.3.0 - feat(core)
|
||||||
|
Enhanced directory handling and file restoration from trash
|
||||||
|
|
||||||
|
- Refined getSubDirectoryByName to handle file paths treated as directories.
|
||||||
|
- Introduced file restoration function from trash to original or specified paths.
|
||||||
|
|
||||||
|
## 2024-11-24 - 3.2.2 - fix(core)
|
||||||
|
Refactor Bucket class for improved error handling
|
||||||
|
|
||||||
|
- Ensured safe access using non-null assertions when finding a bucket.
|
||||||
|
- Enhanced fastPut method by adding fastPutStrict for safer operations.
|
||||||
|
- Added explicit error handling and type checking in fastExists method.
|
||||||
|
|
||||||
## 2024-11-24 - 3.2.1 - fix(metadata)
|
## 2024-11-24 - 3.2.1 - fix(metadata)
|
||||||
Fix metadata handling for deleted files
|
Fix metadata handling for deleted files
|
||||||
|
|
||||||
|
19
license
Normal file
19
license
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
Copyright (c) 2014 Task Venture Capital GmbH (hello@task.vc)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
@ -8,28 +8,30 @@
|
|||||||
"githost": "code.foss.global",
|
"githost": "code.foss.global",
|
||||||
"gitscope": "push.rocks",
|
"gitscope": "push.rocks",
|
||||||
"gitrepo": "smartbucket",
|
"gitrepo": "smartbucket",
|
||||||
"description": "A TypeScript library offering simple and cloud-agnostic object storage with advanced features like bucket creation, file and directory management, and data streaming.",
|
"description": "A TypeScript library providing a cloud-agnostic interface for managing object storage with functionalities like bucket management, file and directory operations, and advanced features such as metadata handling and file locking.",
|
||||||
"npmPackagename": "@push.rocks/smartbucket",
|
"npmPackagename": "@push.rocks/smartbucket",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"TypeScript",
|
"TypeScript",
|
||||||
"cloud storage",
|
"cloud agnostic",
|
||||||
"object storage",
|
"object storage",
|
||||||
"bucket creation",
|
"bucket management",
|
||||||
"file management",
|
"file operations",
|
||||||
"directory management",
|
"directory management",
|
||||||
"data streaming",
|
"data streaming",
|
||||||
"multi-cloud",
|
|
||||||
"API",
|
|
||||||
"unified storage",
|
|
||||||
"S3",
|
"S3",
|
||||||
"minio",
|
"multi-cloud",
|
||||||
"file locking",
|
"file locking",
|
||||||
"metadata",
|
"metadata management",
|
||||||
"buffer handling",
|
"buffer handling",
|
||||||
"access key",
|
"access control",
|
||||||
"secret key",
|
"environment configuration",
|
||||||
"cloud agnostic"
|
"unified storage",
|
||||||
|
"bucket policies",
|
||||||
|
"trash management",
|
||||||
|
"file transfer",
|
||||||
|
"data management",
|
||||||
|
"streaming"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
4
package-lock.json
generated
4
package-lock.json
generated
@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@push.rocks/smartbucket",
|
"name": "@push.rocks/smartbucket",
|
||||||
"version": "3.2.1",
|
"version": "3.3.7",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@push.rocks/smartbucket",
|
"name": "@push.rocks/smartbucket",
|
||||||
"version": "3.2.1",
|
"version": "3.3.7",
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@push.rocks/smartpath": "^5.0.18",
|
"@push.rocks/smartpath": "^5.0.18",
|
||||||
|
32
package.json
32
package.json
@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@push.rocks/smartbucket",
|
"name": "@push.rocks/smartbucket",
|
||||||
"version": "3.2.1",
|
"version": "3.3.7",
|
||||||
"description": "A TypeScript library offering simple and cloud-agnostic object storage with advanced features like bucket creation, file and directory management, and data streaming.",
|
"description": "A TypeScript library providing a cloud-agnostic interface for managing object storage with functionalities like bucket management, file and directory operations, and advanced features such as metadata handling and file locking.",
|
||||||
"main": "dist_ts/index.js",
|
"main": "dist_ts/index.js",
|
||||||
"typings": "dist_ts/index.d.ts",
|
"typings": "dist_ts/index.d.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"author": "Lossless GmbH",
|
"author": "Task Venture Capital GmbH",
|
||||||
"license": "UNLICENSED",
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "(tstest test/)",
|
"test": "(tstest test/)",
|
||||||
"build": "(tsbuild --web --allowimplicitany)"
|
"build": "(tsbuild --web --allowimplicitany)"
|
||||||
@ -47,23 +47,25 @@
|
|||||||
],
|
],
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"TypeScript",
|
"TypeScript",
|
||||||
"cloud storage",
|
"cloud agnostic",
|
||||||
"object storage",
|
"object storage",
|
||||||
"bucket creation",
|
"bucket management",
|
||||||
"file management",
|
"file operations",
|
||||||
"directory management",
|
"directory management",
|
||||||
"data streaming",
|
"data streaming",
|
||||||
"multi-cloud",
|
|
||||||
"API",
|
|
||||||
"unified storage",
|
|
||||||
"S3",
|
"S3",
|
||||||
"minio",
|
"multi-cloud",
|
||||||
"file locking",
|
"file locking",
|
||||||
"metadata",
|
"metadata management",
|
||||||
"buffer handling",
|
"buffer handling",
|
||||||
"access key",
|
"access control",
|
||||||
"secret key",
|
"environment configuration",
|
||||||
"cloud agnostic"
|
"unified storage",
|
||||||
|
"bucket policies",
|
||||||
|
"trash management",
|
||||||
|
"file transfer",
|
||||||
|
"data management",
|
||||||
|
"streaming"
|
||||||
],
|
],
|
||||||
"homepage": "https://code.foss.global/push.rocks/smartbucket",
|
"homepage": "https://code.foss.global/push.rocks/smartbucket",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
@ -1 +1,3 @@
|
|||||||
|
* The project uses the official s3 client, not the minio client.
|
||||||
|
* notice the difference between *Strict methods and the normal methods.
|
||||||
|
* metadata is handled though the MetaData class. Important!
|
||||||
|
339
readme.md
339
readme.md
@ -1,41 +1,49 @@
|
|||||||
|
```markdown
|
||||||
# @push.rocks/smartbucket
|
# @push.rocks/smartbucket
|
||||||
|
|
||||||
A TypeScript library for cloud-independent object storage, providing features like bucket creation, file and directory management, and data streaming.
|
A comprehensive TypeScript library for cloud-agnostic object storage offering bucket management, file operations, and advanced data streaming.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
To install `@push.rocks/smartbucket`, you need to have Node.js and npm (Node Package Manager) installed. If they are installed, you can add `@push.rocks/smartbucket` to your project by running the following command in your project's root directory:
|
To install `@push.rocks/smartbucket`, ensure you have Node.js and npm installed. Then, run the following command in your project directory:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install @push.rocks/smartbucket --save
|
npm install @push.rocks/smartbucket --save
|
||||||
```
|
```
|
||||||
|
|
||||||
This command will download and install `@push.rocks/smartbucket` along with its required dependencies into your project's `node_modules` directory and save it as a dependency in your project's `package.json` file.
|
This command will add `@push.rocks/smartbucket` to your project's dependencies and install it along with its requirements in the `node_modules` directory.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
`@push.rocks/smartbucket` is a TypeScript module designed to provide simple cloud-independent object storage functionality. It wraps various cloud storage providers such as AWS S3, Google Cloud Storage, and others, offering a unified API to manage storage buckets and objects within those buckets.
|
### Introduction
|
||||||
|
|
||||||
In this guide, we will delve into the usage of SmartBucket, covering its full range of features from setting up the library to advanced usage scenarios.
|
`@push.rocks/smartbucket` provides a robust set of features to manage cloud storage operations in a cloud-agnostic manner. By leveraging this library, you can seamlessly interact with object storage services like AWS S3, without being tied to any vendor-specific implementations. This library not only abstracts basic file operations but also integrates advanced capabilities such as metadata management, data streaming, file locking, and bucket policies, all through a simplified API.
|
||||||
|
|
||||||
### Table of Contents
|
### Table of Contents
|
||||||
|
|
||||||
1. [Setting Up](#setting-up)
|
1. [Setting Up](#setting-up)
|
||||||
2. [Creating a New Bucket](#creating-a-new-bucket)
|
2. [Working with Buckets](#working-with-buckets)
|
||||||
3. [Listing Buckets](#listing-buckets)
|
- [Creating a New Bucket](#creating-a-new-bucket)
|
||||||
4. [Working with Files](#working-with-files)
|
- [Listing Buckets](#listing-buckets)
|
||||||
|
- [Deleting Buckets](#deleting-buckets)
|
||||||
|
3. [File Operations in Buckets](#file-operations-in-buckets)
|
||||||
- [Uploading Files](#uploading-files)
|
- [Uploading Files](#uploading-files)
|
||||||
- [Downloading Files](#downloading-files)
|
- [Downloading Files](#downloading-files)
|
||||||
- [Deleting Files](#deleting-files)
|
|
||||||
- [Streaming Files](#streaming-files)
|
- [Streaming Files](#streaming-files)
|
||||||
5. [Working with Directories](#working-with-directories)
|
- [Deleting Files](#deleting-files)
|
||||||
6. [Advanced Features](#advanced-features)
|
4. [Directory Operations](#directory-operations)
|
||||||
|
- [Listing Directories and Files](#listing-directories-and-files)
|
||||||
|
- [Managing Files in Directories](#managing-files-in-directories)
|
||||||
|
5. [Advanced Features](#advanced-features)
|
||||||
- [Bucket Policies](#bucket-policies)
|
- [Bucket Policies](#bucket-policies)
|
||||||
- [Object Metadata](#object-metadata)
|
- [Metadata Management](#metadata-management)
|
||||||
- [Cloud Agnostic](#cloud-agnostic)
|
- [File Locking](#file-locking)
|
||||||
|
- [Trash Management](#trash-management)
|
||||||
|
6. [Cloud Agnosticism](#cloud-agnosticism)
|
||||||
|
|
||||||
### Setting Up
|
### Setting Up
|
||||||
|
|
||||||
First, ensure you are using ECMAScript modules (ESM) and TypeScript in your project for best compatibility. Here's how to import and initialize SmartBucket in a TypeScript file:
|
Begin by importing the necessary classes from the `@push.rocks/smartbucket` package into your TypeScript file. Create an instance of `SmartBucket` with your storage configuration:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import {
|
import {
|
||||||
@ -49,264 +57,223 @@ const mySmartBucket = new SmartBucket({
|
|||||||
accessKey: "yourAccessKey",
|
accessKey: "yourAccessKey",
|
||||||
accessSecret: "yourSecretKey",
|
accessSecret: "yourSecretKey",
|
||||||
endpoint: "yourEndpointURL",
|
endpoint: "yourEndpointURL",
|
||||||
port: 443, // Default is 443, can be customized for specific endpoint
|
port: 443,
|
||||||
useSsl: true // Defaults to true
|
useSsl: true
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Make sure to replace `"yourAccessKey"`, `"yourSecretKey"`, and `"yourEndpointURL"` with your actual credentials and endpoint URL. The `port` and `useSsl` options are optional and can be omitted if the defaults are acceptable.
|
Replace `"yourAccessKey"`, `"yourSecretKey"`, and `"yourEndpointURL"` with actual data specific to your cloud provider.
|
||||||
|
|
||||||
### Creating a New Bucket
|
### Working with Buckets
|
||||||
|
|
||||||
To create a new bucket:
|
#### Creating a New Bucket
|
||||||
|
|
||||||
|
Creating a bucket involves invoking the `createBucket` method. Note that bucket names are unique and follow the rules of the cloud provider:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function createBucket(bucketName: string) {
|
async function createBucket(bucketName: string) {
|
||||||
try {
|
try {
|
||||||
const myBucket: Bucket = await mySmartBucket.createBucket(bucketName);
|
const newBucket: Bucket = await mySmartBucket.createBucket(bucketName);
|
||||||
console.log(`Bucket ${bucketName} created successfully.`);
|
console.log(`Bucket ${bucketName} created successfully.`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error creating bucket:", error);
|
console.error("Error creating bucket:", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
createBucket("myNewBucket");
|
||||||
createBucket("exampleBucket");
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Bucket names must be unique across the storage service.
|
#### Listing Buckets
|
||||||
|
|
||||||
### Listing Buckets
|
While the library uses cloud-provider capabilities like AWS SDK to list existing buckets, `smartbucket` is aimed at simplifying content management within them.
|
||||||
|
|
||||||
Currently, SmartBucket does not include a direct method to list all buckets, but you can access the underlying client provided by the cloud storage SDK to perform such operations, depending on the SDK's capabilities.
|
#### Deleting Buckets
|
||||||
|
|
||||||
### Working with Files
|
To delete a bucket, simply call the `removeBucket` function:
|
||||||
|
|
||||||
#### Uploading Files
|
|
||||||
|
|
||||||
To upload an object to a bucket:
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function uploadFile(bucketName: string, filePath: string, fileContent: Buffer | string) {
|
async function deleteBucket(bucketName: string) {
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
try {
|
||||||
if (myBucket) {
|
await mySmartBucket.removeBucket(bucketName);
|
||||||
await myBucket.fastPut({ path: filePath, contents: fileContent });
|
console.log(`Bucket ${bucketName} deleted successfully.`);
|
||||||
console.log(`File uploaded to ${bucketName} at ${filePath}`);
|
} catch (error) {
|
||||||
} else {
|
console.error("Error deleting bucket:", error);
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
deleteBucket("anotherBucketName");
|
||||||
uploadFile("exampleBucket", "path/to/object.txt", "Hello, world!");
|
```
|
||||||
|
|
||||||
|
### File Operations in Buckets
|
||||||
|
|
||||||
|
SmartBucket offers a unified API to execute file-based operations efficiently.
|
||||||
|
|
||||||
|
#### Uploading Files
|
||||||
|
|
||||||
|
Upload a file using the `fastPut` method, specifying the bucket name, file path, and content:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async function uploadFile(bucketName: string, filePath: string, fileContent: Buffer | string) {
|
||||||
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
|
await bucket.fastPut({ path: filePath, contents: fileContent });
|
||||||
|
console.log(`File uploaded to ${filePath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
uploadFile("myBucket", "example.txt", "This is a sample file content.");
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Downloading Files
|
#### Downloading Files
|
||||||
|
|
||||||
To download an object:
|
Download files using `fastGet`. It retrieves the file content as a buffer:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function downloadFile(bucketName: string, filePath: string) {
|
async function downloadFile(bucketName: string, filePath: string) {
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
if (myBucket) {
|
const content: Buffer = await bucket.fastGet({ path: filePath });
|
||||||
const fileContent: Buffer = await myBucket.fastGet({ path: filePath });
|
console.log("Downloaded content:", content.toString());
|
||||||
console.log("Downloaded file content:", fileContent.toString());
|
|
||||||
} else {
|
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
downloadFile("myBucket", "example.txt");
|
||||||
downloadFile("exampleBucket", "path/to/object.txt");
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Deleting Files
|
|
||||||
|
|
||||||
To delete an object from a bucket:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
async function deleteFile(bucketName: string, filePath: string) {
|
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
|
||||||
if (myBucket) {
|
|
||||||
await myBucket.fastRemove({ path: filePath });
|
|
||||||
console.log(`File at ${filePath} deleted from ${bucketName}.`);
|
|
||||||
} else {
|
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use the function
|
|
||||||
deleteFile("exampleBucket", "path/to/object.txt");
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Streaming Files
|
#### Streaming Files
|
||||||
|
|
||||||
SmartBucket allows you to work with file streams, which can be useful for handling large files.
|
For large-scale applications, stream files without loading them fully into memory:
|
||||||
|
|
||||||
To read a file as a stream:
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { ReplaySubject } from '@push.rocks/smartrx';
|
async function streamFile(bucketName: string, filePath: string) {
|
||||||
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
async function readFileStream(bucketName: string, filePath: string) {
|
const stream = await bucket.fastGetStream({ path: filePath }, "nodestream");
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
stream.on('data', chunk => console.log("Chunk:", chunk.toString()));
|
||||||
if (myBucket) {
|
stream.on('end', () => console.log("Download completed."));
|
||||||
const fileStream: ReplaySubject<Buffer> = await myBucket.fastGetStream({ path: filePath });
|
|
||||||
fileStream.subscribe({
|
|
||||||
next(chunk: Buffer) {
|
|
||||||
console.log("Chunk received:", chunk.toString());
|
|
||||||
},
|
|
||||||
complete() {
|
|
||||||
console.log("File read completed.");
|
|
||||||
},
|
|
||||||
error(err) {
|
|
||||||
console.error("Error reading file stream:", err);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
streamFile("myBucket", "largefile.txt");
|
||||||
readFileStream("exampleBucket", "path/to/object.txt");
|
|
||||||
```
|
```
|
||||||
|
|
||||||
To write a file as a stream:
|
#### Deleting Files
|
||||||
|
|
||||||
|
Delete files with precision using `fastRemove`:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Readable } from 'stream';
|
async function deleteFile(bucketName: string, filePath: string) {
|
||||||
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
async function writeFileStream(bucketName: string, filePath: string, readableStream: Readable) {
|
await bucket.fastRemove({ path: filePath });
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
console.log(`File ${filePath} deleted.`);
|
||||||
if (myBucket) {
|
|
||||||
await myBucket.fastPutStream({ path: filePath, dataStream: readableStream });
|
|
||||||
console.log(`File streamed to ${bucketName} at ${filePath}`);
|
|
||||||
} else {
|
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a readable stream from a string
|
deleteFile("myBucket", "example.txt");
|
||||||
const readable = new Readable();
|
|
||||||
readable.push('Hello world streamed as a file!');
|
|
||||||
readable.push(null); // End of stream
|
|
||||||
|
|
||||||
// Use the function
|
|
||||||
writeFileStream("exampleBucket", "path/to/streamedObject.txt", readable);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Working with Directories
|
### Directory Operations
|
||||||
|
|
||||||
`@push.rocks/smartbucket` offers abstractions for directories within buckets for easier object management. You can create, list, and delete directories using the `Directory` class.
|
Leverage directory functionalities to better organize and manage files within buckets.
|
||||||
|
|
||||||
To list the contents of a directory:
|
#### Listing Directories and Files
|
||||||
|
|
||||||
|
Listing contents showcases a directory’s structure and file contents:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function listDirectoryContents(bucketName: string, directoryPath: string) {
|
async function listDirectory(bucketName: string, directoryPath: string) {
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
if (myBucket) {
|
const baseDirectory: Directory = await bucket.getBaseDirectory();
|
||||||
const baseDirectory: Directory = await myBucket.getBaseDirectory();
|
const targetDirectory = await baseDirectory.getSubDirectoryByName(directoryPath);
|
||||||
const targetDirectory: Directory = await baseDirectory.getSubDirectoryByName(directoryPath);
|
|
||||||
|
|
||||||
console.log('Listing directories:');
|
|
||||||
const directories = await targetDirectory.listDirectories();
|
|
||||||
directories.forEach(dir => {
|
|
||||||
console.log(`- ${dir.name}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Listing files:');
|
console.log('Directories:');
|
||||||
const files = await targetDirectory.listFiles();
|
(await targetDirectory.listDirectories()).forEach(dir => console.log(dir.name));
|
||||||
files.forEach(file => {
|
|
||||||
console.log(`- ${file.name}`);
|
console.log('Files:');
|
||||||
});
|
(await targetDirectory.listFiles()).forEach(file => console.log(file.name));
|
||||||
} else {
|
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
listDirectory("myBucket", "path/to/directory");
|
||||||
listDirectoryContents("exampleBucket", "some/directory/path");
|
|
||||||
```
|
```
|
||||||
|
|
||||||
To create a file within a directory:
|
#### Managing Files in Directories
|
||||||
|
|
||||||
|
Additional functionalities allow file management, inclusive of handling sub-directories:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function createFileInDirectory(bucketName: string, directoryPath: string, fileName: string, fileContent: string) {
|
async function manageFilesInDirectory(bucketName: string, directoryPath: string, fileName: string, content: string) {
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
if (myBucket) {
|
const baseDirectory: Directory = await bucket.getBaseDirectory();
|
||||||
const baseDirectory: Directory = await myBucket.getBaseDirectory();
|
const directory = await baseDirectory.getSubDirectoryByName(directoryPath) ?? baseDirectory;
|
||||||
const targetDirectory: Directory = await baseDirectory.getSubDirectoryByName(directoryPath);
|
|
||||||
await targetDirectory.createEmptyFile(fileName); // Create an empty file
|
await directory.fastPut({ path: fileName, contents: content });
|
||||||
const file = new File({ directoryRefArg: targetDirectory, fileName });
|
console.log(`File ${fileName} created in ${directoryPath}`);
|
||||||
await file.updateWithContents({ contents: fileContent });
|
|
||||||
console.log(`File created: ${fileName}`);
|
const fileContent = await directory.fastGet({ path: fileName });
|
||||||
} else {
|
console.log(`Content of ${fileName}: ${fileContent.toString()}`);
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
manageFilesInDirectory("myBucket", "myDir", "example.txt", "File content here");
|
||||||
createFileInDirectory("exampleBucket", "some/directory", "newfile.txt", "Hello, world!");
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Advanced Features
|
### Advanced Features
|
||||||
|
|
||||||
|
The library’s advanced features streamline intricate cloud storage workflows.
|
||||||
|
|
||||||
#### Bucket Policies
|
#### Bucket Policies
|
||||||
|
|
||||||
Manage bucket policies to control access permissions. This feature depends on the policies provided by the storage service (e.g., AWS S3, MinIO).
|
The library offers tools for maintaining consistent bucket policies across storage providers, assisting in defining access roles and permissions.
|
||||||
|
|
||||||
#### Object Metadata
|
#### Metadata Management
|
||||||
|
|
||||||
Retrieve and modify object metadata. Metadata can be useful for storing additional information about an object.
|
Easily manage and store metadata by using the `MetaData` utility:
|
||||||
|
|
||||||
To retrieve metadata:
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function getObjectMetadata(bucketName: string, filePath: string) {
|
async function handleMetadata(bucketName: string, filePath: string) {
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
if (myBucket) {
|
const meta = await bucket.fastStat({ path: filePath });
|
||||||
const metadata = await mySmartBucket.minioClient.statObject(bucketName, filePath);
|
console.log("Metadata:", meta.Metadata);
|
||||||
console.log("Object metadata:", metadata);
|
|
||||||
} else {
|
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
handleMetadata("myBucket", "example.txt");
|
||||||
getObjectMetadata("exampleBucket", "path/to/object.txt");
|
|
||||||
```
|
```
|
||||||
|
|
||||||
To update metadata:
|
#### File Locking
|
||||||
|
|
||||||
|
Prevent accidental writes by locking files:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function updateObjectMetadata(bucketName: string, filePath: string, newMetadata: { [key: string]: string }) {
|
async function lockFile(bucketName: string, filePath: string) {
|
||||||
const myBucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
if (myBucket) {
|
const file: File = await bucket.getBaseDirectory().getFileStrict({ path: filePath });
|
||||||
await myBucket.copyObject({
|
await file.lock({ timeoutMillis: 600000 }); // Lock for 10 minutes
|
||||||
objectKey: filePath,
|
console.log(`File ${filePath} locked.`);
|
||||||
nativeMetadata: newMetadata,
|
|
||||||
deleteExistingNativeMetadata: false,
|
|
||||||
});
|
|
||||||
console.log(`Metadata updated for ${filePath}`);
|
|
||||||
} else {
|
|
||||||
console.error(`Bucket ${bucketName} does not exist.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the function
|
lockFile("myBucket", "example.txt");
|
||||||
updateObjectMetadata("exampleBucket", "path/to/object.txt", {
|
|
||||||
customKey: "customValue"
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Cloud Agnostic
|
#### Trash Management
|
||||||
|
|
||||||
`@push.rocks/smartbucket` is designed to work with multiple cloud providers, allowing for easier migration or multi-cloud strategies. This means you can switch from one provider to another with minimal changes to your codebase.
|
SmartBucket enables a safe deletion mode where files can be moved to a recycling bin, allowing for restoration:
|
||||||
|
|
||||||
Remember, each cloud provider has specific features and limitations. `@push.rocks/smartbucket` aims to abstract common functionalities, but always refer to the specific cloud provider's documentation for advanced features or limitations.
|
```typescript
|
||||||
|
async function trashAndRestoreFile(bucketName: string, filePath: string) {
|
||||||
|
const bucket: Bucket = await mySmartBucket.getBucketByName(bucketName);
|
||||||
|
const file: File = await bucket.getBaseDirectory().getFileStrict({ path: filePath });
|
||||||
|
|
||||||
This guide covers the basic to advanced scenarios of using `@push.rocks/smartbucket`. For further details, refer to the API documentation and examples.
|
// Move the file to trash
|
||||||
|
await file.delete({ mode: 'trash' });
|
||||||
|
console.log(`File ${filePath} moved to trash.`);
|
||||||
|
|
||||||
|
// Retrieve the file from the trash
|
||||||
|
const trashFile = await bucket.getTrash().getTrashedFileByOriginalName({ path: filePath });
|
||||||
|
await trashFile.restore();
|
||||||
|
console.log(`File ${filePath} restored from trash.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
trashAndRestoreFile("myBucket", "example.txt");
|
||||||
|
```
|
||||||
|
|
||||||
|
### Cloud Agnosticism
|
||||||
|
|
||||||
|
`@push.rocks/smartbucket` supports a multitude of cloud providers, enhancing flexibility in adopting different cloud strategies without the need for extensive code rewrite. It offers a uniform interface allowing to perform operations seamlessly between different storage solutions such as AWS S3, Google Cloud Storage, and more. This aspect empowers organizations to align their storage decisions with business needs rather than technical constraints.
|
||||||
|
|
||||||
|
By following this guide, you should be well-equipped to handle cloud storage operations using the `@push.rocks/smartbucket` library. Diligently constructed code examples elucidate the extensive functionalities offered by the library, aligned with best practices in cloud storage. For a deeper dive into any specific feature, refer to the comprehensive documentation provided with the library and the official documentation of the cloud providers you are integrating with.
|
||||||
|
```
|
||||||
|
|
||||||
## License and Legal Information
|
## License and Legal Information
|
||||||
|
|
||||||
|
@ -30,7 +30,7 @@ tap.test('should clean all contents', async () => {
|
|||||||
|
|
||||||
tap.test('should delete a file into the normally', async () => {
|
tap.test('should delete a file into the normally', async () => {
|
||||||
const path = 'trashtest/trashme.txt';
|
const path = 'trashtest/trashme.txt';
|
||||||
const file = await myBucket.fastPut({
|
const file = await myBucket.fastPutStrict({
|
||||||
path,
|
path,
|
||||||
contents: 'I\'m in the trash test content!',
|
contents: 'I\'m in the trash test content!',
|
||||||
});
|
});
|
||||||
@ -44,7 +44,7 @@ tap.test('should delete a file into the normally', async () => {
|
|||||||
|
|
||||||
tap.test('should put a file into the trash', async () => {
|
tap.test('should put a file into the trash', async () => {
|
||||||
const path = 'trashtest/trashme.txt';
|
const path = 'trashtest/trashme.txt';
|
||||||
const file = await myBucket.fastPut({
|
const file = await myBucket.fastPutStrict({
|
||||||
path,
|
path,
|
||||||
contents: 'I\'m in the trash test content!',
|
contents: 'I\'m in the trash test content!',
|
||||||
});
|
});
|
||||||
@ -52,7 +52,21 @@ tap.test('should put a file into the trash', async () => {
|
|||||||
console.log(fileMetadata.toString());
|
console.log(fileMetadata.toString());
|
||||||
expect(await file.getMetaData().then((meta) => meta.metadataFile.getJsonData())).toEqual({});
|
expect(await file.getMetaData().then((meta) => meta.metadataFile.getJsonData())).toEqual({});
|
||||||
await file.delete({ mode: 'trash' });
|
await file.delete({ mode: 'trash' });
|
||||||
jestExpect(await file.getMetaData().then((meta) => meta.metadataFile.getJsonData())).toEqual({
|
|
||||||
|
const getTrashContents = async () => {
|
||||||
|
const trash = await myBucket.getTrash();
|
||||||
|
const trashDir = await trash.getTrashDir();
|
||||||
|
return await trashDir.listFiles();
|
||||||
|
}
|
||||||
|
|
||||||
|
const trashedFiles = await getTrashContents();
|
||||||
|
expect(trashedFiles.length).toEqual(2);
|
||||||
|
|
||||||
|
const trashedMetaFile = trashedFiles.find(file => file.name.endsWith('.metadata'));
|
||||||
|
expect(trashedMetaFile).toBeDefined();
|
||||||
|
expect(trashedMetaFile).toBeInstanceOf(smartbucket.File);
|
||||||
|
|
||||||
|
jestExpect(await trashedMetaFile!.getJsonData()).toEqual({
|
||||||
custom_recycle: {
|
custom_recycle: {
|
||||||
deletedAt: jestExpect.any(Number),
|
deletedAt: jestExpect.any(Number),
|
||||||
originalPath: "trashtest/trashme.txt",
|
originalPath: "trashtest/trashme.txt",
|
||||||
@ -60,4 +74,19 @@ tap.test('should put a file into the trash', async () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
tap.test('should restore a file from trash', async () => {
|
||||||
|
const baseDirectory = await myBucket.getBaseDirectory();
|
||||||
|
const file = await baseDirectory.getFileStrict({
|
||||||
|
path: 'trashtest/trashme.txt',
|
||||||
|
getFromTrash: true
|
||||||
|
});
|
||||||
|
const trashFileMeta = await file.getMetaData();
|
||||||
|
const data = await trashFileMeta.getCustomMetaData({
|
||||||
|
key: 'recycle'
|
||||||
|
});
|
||||||
|
expect(file).toBeInstanceOf(smartbucket.File);
|
||||||
|
await file.restore();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
export default tap.start();
|
export default tap.start();
|
||||||
|
@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smartbucket',
|
name: '@push.rocks/smartbucket',
|
||||||
version: '3.2.1',
|
version: '3.3.7',
|
||||||
description: 'A TypeScript library offering simple and cloud-agnostic object storage with advanced features like bucket creation, file and directory management, and data streaming.'
|
description: 'A TypeScript library providing a cloud-agnostic interface for managing object storage with functionalities like bucket management, file and directory operations, and advanced features such as metadata handling and file locking.'
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@ export class Bucket {
|
|||||||
public static async getBucketByName(smartbucketRef: SmartBucket, bucketNameArg: string) {
|
public static async getBucketByName(smartbucketRef: SmartBucket, bucketNameArg: string) {
|
||||||
const command = new plugins.s3.ListBucketsCommand({});
|
const command = new plugins.s3.ListBucketsCommand({});
|
||||||
const buckets = await smartbucketRef.s3Client.send(command);
|
const buckets = await smartbucketRef.s3Client.send(command);
|
||||||
const foundBucket = buckets.Buckets.find((bucket) => bucket.Name === bucketNameArg);
|
const foundBucket = buckets.Buckets!.find((bucket) => bucket.Name === bucketNameArg);
|
||||||
|
|
||||||
if (foundBucket) {
|
if (foundBucket) {
|
||||||
console.log(`bucket with name ${bucketNameArg} exists.`);
|
console.log(`bucket with name ${bucketNameArg} exists.`);
|
||||||
@ -88,14 +88,15 @@ export class Bucket {
|
|||||||
contents: string | Buffer;
|
contents: string | Buffer;
|
||||||
overwrite?: boolean;
|
overwrite?: boolean;
|
||||||
}
|
}
|
||||||
): Promise<File> {
|
): Promise<File | null> {
|
||||||
try {
|
try {
|
||||||
const reducedPath = await helpers.reducePathDescriptorToPath(optionsArg);
|
const reducedPath = await helpers.reducePathDescriptorToPath(optionsArg);
|
||||||
const exists = await this.fastExists({ path: reducedPath });
|
const exists = await this.fastExists({ path: reducedPath });
|
||||||
|
|
||||||
if (exists && !optionsArg.overwrite) {
|
if (exists && !optionsArg.overwrite) {
|
||||||
console.error(`Object already exists at path '${reducedPath}' in bucket '${this.name}'.`);
|
const errorText = `Object already exists at path '${reducedPath}' in bucket '${this.name}'.`;
|
||||||
return;
|
console.error(errorText);
|
||||||
|
return null;
|
||||||
} else if (exists && optionsArg.overwrite) {
|
} else if (exists && optionsArg.overwrite) {
|
||||||
console.log(
|
console.log(
|
||||||
`Overwriting existing object at path '${reducedPath}' in bucket '${this.name}'.`
|
`Overwriting existing object at path '${reducedPath}' in bucket '${this.name}'.`
|
||||||
@ -128,6 +129,14 @@ export class Bucket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async fastPutStrict(...args: Parameters<Bucket['fastPut']>) {
|
||||||
|
const file = await this.fastPut(...args);
|
||||||
|
if (!file) {
|
||||||
|
throw new Error(`File not stored at path '${args[0].path}'`);
|
||||||
|
}
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get file
|
* get file
|
||||||
*/
|
*/
|
||||||
@ -152,7 +161,7 @@ export class Bucket {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
await done.promise;
|
await done.promise;
|
||||||
return completeFile;
|
return completeFile!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -220,7 +229,7 @@ export class Bucket {
|
|||||||
return chunk;
|
return chunk;
|
||||||
},
|
},
|
||||||
finalFunction: async (cb) => {
|
finalFunction: async (cb) => {
|
||||||
return null;
|
return null!;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -392,8 +401,8 @@ export class Bucket {
|
|||||||
await this.smartbucketRef.s3Client.send(command);
|
await this.smartbucketRef.s3Client.send(command);
|
||||||
console.log(`Object '${optionsArg.path}' exists in bucket '${this.name}'.`);
|
console.log(`Object '${optionsArg.path}' exists in bucket '${this.name}'.`);
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
if (error.name === 'NotFound') {
|
if (error?.name === 'NotFound') {
|
||||||
console.log(`Object '${optionsArg.path}' does not exist in bucket '${this.name}'.`);
|
console.log(`Object '${optionsArg.path}' does not exist in bucket '${this.name}'.`);
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
|
@ -10,9 +10,9 @@ export class Directory {
|
|||||||
public parentDirectoryRef: Directory;
|
public parentDirectoryRef: Directory;
|
||||||
public name: string;
|
public name: string;
|
||||||
|
|
||||||
public tree: string[];
|
public tree!: string[];
|
||||||
public files: string[];
|
public files!: string[];
|
||||||
public folders: string[];
|
public folders!: string[];
|
||||||
|
|
||||||
constructor(bucketRefArg: Bucket, parentDirectory: Directory, name: string) {
|
constructor(bucketRefArg: Bucket, parentDirectory: Directory, name: string) {
|
||||||
this.bucketRef = bucketRefArg;
|
this.bucketRef = bucketRefArg;
|
||||||
@ -192,9 +192,22 @@ export class Directory {
|
|||||||
* gets a sub directory by name
|
* gets a sub directory by name
|
||||||
*/
|
*/
|
||||||
public async getSubDirectoryByName(dirNameArg: string, optionsArg: {
|
public async getSubDirectoryByName(dirNameArg: string, optionsArg: {
|
||||||
|
/**
|
||||||
|
* in s3 a directory does not exist if it is empty
|
||||||
|
* this option returns a directory even if it is empty
|
||||||
|
*/
|
||||||
getEmptyDirectory?: boolean;
|
getEmptyDirectory?: boolean;
|
||||||
|
/**
|
||||||
|
* in s3 a directory does not exist if it is empty
|
||||||
|
* this option creates a directory even if it is empty using a initializer file
|
||||||
|
*/
|
||||||
createWithInitializerFile?: boolean;
|
createWithInitializerFile?: boolean;
|
||||||
|
/**
|
||||||
|
* if the path is a file path, it will be treated as a file and the parent directory will be returned
|
||||||
|
*/
|
||||||
|
couldBeFilePath?: boolean;
|
||||||
} = {}): Promise<Directory | null> {
|
} = {}): Promise<Directory | null> {
|
||||||
|
|
||||||
const dirNameArray = dirNameArg.split('/').filter(str => str.trim() !== "");
|
const dirNameArray = dirNameArg.split('/').filter(str => str.trim() !== "");
|
||||||
|
|
||||||
optionsArg = {
|
optionsArg = {
|
||||||
@ -221,8 +234,19 @@ export class Directory {
|
|||||||
return returnDirectory || null;
|
return returnDirectory || null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (optionsArg.couldBeFilePath) {
|
||||||
|
const baseDirectory = await this.bucketRef.getBaseDirectory();
|
||||||
|
const existingFile = await baseDirectory.getFile({
|
||||||
|
path: dirNameArg,
|
||||||
|
});
|
||||||
|
if (existingFile) {
|
||||||
|
const adjustedPath = dirNameArg.substring(0, dirNameArg.lastIndexOf('/'));
|
||||||
|
return this.getSubDirectoryByName(adjustedPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let wantedDirectory: Directory | null = null;
|
let wantedDirectory: Directory | null = null;
|
||||||
let counter = 0;
|
let counter = 0;
|
||||||
for (const dirNameToSearch of dirNameArray) {
|
for (const dirNameToSearch of dirNameArray) {
|
||||||
counter++;
|
counter++;
|
||||||
const directoryToSearchIn = wantedDirectory ? wantedDirectory : this;
|
const directoryToSearchIn = wantedDirectory ? wantedDirectory : this;
|
||||||
@ -336,7 +360,7 @@ export class Directory {
|
|||||||
*/
|
*/
|
||||||
mode?: 'permanent' | 'trash';
|
mode?: 'permanent' | 'trash';
|
||||||
}) {
|
}) {
|
||||||
const file = await this.getFile({
|
const file = await this.getFileStrict({
|
||||||
path: optionsArg.path,
|
path: optionsArg.path,
|
||||||
});
|
});
|
||||||
await file.delete({
|
await file.delete({
|
||||||
|
@ -130,6 +130,33 @@ export class File {
|
|||||||
await this.parentDirectoryRef.listFiles();
|
await this.parentDirectoryRef.listFiles();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* restores
|
||||||
|
*/
|
||||||
|
public async restore(optionsArg: {
|
||||||
|
useOriginalPath?: boolean;
|
||||||
|
toPath?: string;
|
||||||
|
overwrite?: boolean;
|
||||||
|
} = {}) {
|
||||||
|
optionsArg = {
|
||||||
|
useOriginalPath: (() => {
|
||||||
|
return optionsArg.toPath ? false : true;
|
||||||
|
})(),
|
||||||
|
overwrite: false,
|
||||||
|
...optionsArg,
|
||||||
|
};
|
||||||
|
const metadata = await this.getMetaData();
|
||||||
|
const moveToPath = optionsArg.toPath || (await metadata.getCustomMetaData({
|
||||||
|
key: 'recycle'
|
||||||
|
})).originalPath;
|
||||||
|
await metadata.deleteCustomMetaData({
|
||||||
|
key: 'recycle'
|
||||||
|
})
|
||||||
|
await this.move({
|
||||||
|
path: moveToPath,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* allows locking the file
|
* allows locking the file
|
||||||
* @param optionsArg
|
* @param optionsArg
|
||||||
@ -154,7 +181,7 @@ export class File {
|
|||||||
}) {
|
}) {
|
||||||
const metadata = await this.getMetaData();
|
const metadata = await this.getMetaData();
|
||||||
await metadata.removeLock({
|
await metadata.removeLock({
|
||||||
force: optionsArg?.force,
|
force: optionsArg?.force || false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -219,7 +246,10 @@ export class File {
|
|||||||
// lets update references of this
|
// lets update references of this
|
||||||
const baseDirectory = await this.parentDirectoryRef.bucketRef.getBaseDirectory();
|
const baseDirectory = await this.parentDirectoryRef.bucketRef.getBaseDirectory();
|
||||||
this.parentDirectoryRef = await baseDirectory.getSubDirectoryByNameStrict(
|
this.parentDirectoryRef = await baseDirectory.getSubDirectoryByNameStrict(
|
||||||
pathDescriptorArg.directory?.getBasePath()!
|
await helpers.reducePathDescriptorToPath(pathDescriptorArg),
|
||||||
|
{
|
||||||
|
couldBeFilePath: true,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
this.name = pathDescriptorArg.path!;
|
this.name = pathDescriptorArg.path!;
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user