|
| 1 | +import { Injectable } from '@nestjs/common'; |
| 2 | +import { existsSync, mkdir, readFile, writeFile } from 'fs'; |
| 3 | + |
| 4 | +const localPath = 'data/'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Storage provider for local file system |
| 8 | + * Uses the file system on the host machine |
| 9 | + * to store and retrieve files |
| 10 | + * |
| 11 | + * @extends StorageProvider |
| 12 | + */ |
| 13 | +@Injectable() |
| 14 | +export class StorageLocalProviderService { |
| 15 | + private isInitialized = false; |
| 16 | + |
| 17 | + /** |
| 18 | + * Initializes the local storage provider |
| 19 | + * Creates the data directory if it does not exist |
| 20 | + */ |
| 21 | + private initialize(): void { |
| 22 | + if (!this.isInitialized && !existsSync(localPath)) { |
| 23 | + mkdir(localPath, (err) => { |
| 24 | + if (err) |
| 25 | + console.error('Failed to initialize local storage provider: ', err); |
| 26 | + else this.isInitialized = true; |
| 27 | + }); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Fetches a file from the local storage provider |
| 33 | + * |
| 34 | + * @param path the path to the file to fetch |
| 35 | + * @returns if the file was fetched successfully, and the contents of the file |
| 36 | + */ |
| 37 | + public async get(path: string): Promise<{ success: boolean; data: string }> { |
| 38 | + this.initialize(); |
| 39 | + |
| 40 | + return new Promise((resolve, reject) => { |
| 41 | + readFile(localPath + path, (err, data) => { |
| 42 | + if (err) { |
| 43 | + console.error( |
| 44 | + 'Failed to get file from local storage provider: ', |
| 45 | + err, |
| 46 | + ); |
| 47 | + reject({ success: false, data: null }); |
| 48 | + } else { |
| 49 | + resolve({ success: true, data: data.toString() }); |
| 50 | + } |
| 51 | + }); |
| 52 | + }); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Sets a file in the local storage provider |
| 57 | + * |
| 58 | + * @param path the path to the file to set |
| 59 | + * @param value the value to set the file to |
| 60 | + * @returns true if the file was set successfully |
| 61 | + */ |
| 62 | + public async set(path: string, value: any): Promise<boolean> { |
| 63 | + this.initialize(); |
| 64 | + |
| 65 | + if (!existsSync(localPath + path)) { |
| 66 | + return new Promise((resolve, reject) => { |
| 67 | + reject('File does not exist'); |
| 68 | + }); |
| 69 | + } |
| 70 | + |
| 71 | + return new Promise((resolve, reject) => { |
| 72 | + writeFile(localPath + path, value, (err) => { |
| 73 | + if (err) { |
| 74 | + console.error('Failed to set file in local storage provider: ', err); |
| 75 | + return reject(false); |
| 76 | + } else resolve(true); |
| 77 | + }); |
| 78 | + }); |
| 79 | + } |
| 80 | +} |
0 commit comments