anote

Форк
0
/
Saver.ts 
117 строк · 4.0 Кб
1
import { YBucket, YBucketItem, YResponse } from "../types/Types";
2
import { getBuffer } from "../utils/Util";
3

4
const config = require('config');
5
const EasyYandexS3 = require("easy-yandex-s3");
6

7
export default class Saver {
8

9
    readonly s3 = new EasyYandexS3({
10
        auth: {
11
            accessKeyId: config.get("accessKeyId"),
12
            secretAccessKey: config.get("secretAccessKey"),
13
        },
14
        Bucket: config.get("bucket"),
15
        debug: true
16
    });
17

18
    private localStorage: string[] = [];
19
    
20
    setValue(val:string) {
21
        this.localStorage.push(val);
22
    }
23

24
    getValues(): string[] {
25
        return this.localStorage;
26
    }
27

28
    getLastValue(): string {
29
        return this.getValues()[this.localStorage.length - 1];
30
    }
31

32
    async set(){
33
        await this.s3.Upload({path: "../test/file.rtf", name: 'test.rtf'}, "/default/");
34
    }
35

36
    async deleteFile(path: string): Promise<boolean> {
37
        return await this.s3.Remove(path);
38
    }
39

40
   async uploadFileFromBuffer(file_buffer: Buffer, targetDirName: string = "default"): Promise<void> {
41
        await this.s3.Upload({buffer: file_buffer}, `/${targetDirName}/`);
42
   }
43

44
   async uploadFile(
45
        sourceFilePath: string = "../templates/newNote.json",
46
        targetFileName: string,
47
        targetDirName: string = "default"
48
    ): Promise<any> {
49
        return await this.s3.Upload({path: sourceFilePath, name: targetFileName}, `/${targetDirName}/`);
50
   }
51

52
   async uploadBuffer(fileName: string, data: string, path: string = "/"): Promise<YResponse> {
53
       return await this.s3.Upload({buffer: getBuffer(data), name: fileName}, path);
54
   }
55

56
   async downloadFromBuffer(backetPath: string): Promise<string> {
57
        const buffer = await this.s3.Download(backetPath);
58
        if(!Object.keys(buffer).includes("data")) {
59
            return "The specified key does not exist";
60
        }
61
        return buffer.data.Body.toString("utf8");
62
   }
63

64
   async download(backetPath: string, localPath: string): Promise<any> {
65
        return await this.s3.Download(backetPath, localPath);
66
   }
67

68
   async downloadBuffer(filePath: string): Promise<Buffer> {
69
       return await this.s3.Download(filePath);
70
   }
71

72
   async appendLine(baseFileName: string, addedString: string, baseFileLocation: string = "/") {
73
      const saver: Saver = new Saver();
74
      const baseBuffer: string = await saver.downloadFromBuffer(baseFileName);
75
      const final: string = baseBuffer + "\n" + addedString;
76
      const response: YResponse = await saver.uploadBuffer(baseFileName, final, baseFileLocation);
77
      return response.Location;
78
   }
79

80
   async createFolder(name: string) {
81
       await this.s3.Upload(`/${name}`);
82
   }
83

84
    async list(pointer: string = '/'): Promise<string[]>{
85
        const bucketContent: YBucket = await this.s3.GetList(pointer);
86
        if(bucketContent.KeyCount === 0){
87
            return [];
88
        }
89
        const files: string[] = bucketContent.Contents.map(file => file.Key);
90
        const folders: string[] = bucketContent.CommonPrefixes.map(folder => folder.Prefix);
91
        return [...folders, ...files];
92
    }
93

94
    async listAll(): Promise<string[]> {
95
        const bucketContent: YBucket = await this.s3.GetList('/');
96
        if(bucketContent.KeyCount === 0) return [];
97
        const rootFolders: string[] = bucketContent.CommonPrefixes.map(folder => folder.Prefix);
98
        const allFolders: string[] = await this.getFolders(rootFolders);
99
        let allElements: string[] = [];
100
        for(const folder of allFolders) {
101
            const bucketContent: YBucket = await this.s3.GetList(folder);
102
            allElements.push(...bucketContent.Contents.map(file => file.Key));
103
        }
104
        return allElements;
105
    }
106

107
    private async getFolders(folders: string[]): Promise<string[]> {
108
        let result: string[] = folders;
109
        for(const folder of folders) {
110
                if(folder !== "/") {
111
                    const bucketContent: YBucket = await this.s3.GetList(folder);
112
                    result.push(...bucketContent.CommonPrefixes.map(f => f.Prefix));    
113
                }
114
        }
115
        return result;
116
    }
117
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.