UNPKG

@filesrocket/local

Version:

Filesrocket service that manages your files locally

71 lines 3.1 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.LocalService = void 0; const fs_1 = require("fs"); const http_errors_1 = require("http-errors"); const util_1 = require("util"); const path_1 = __importDefault(require("path")); const directory_service_1 = require("./services/directory.service"); const base_service_1 = require("./services/base.service"); const helpers_1 = require("./helpers"); const readdirAsync = (0, util_1.promisify)(fs_1.readdir); const unlinkAsync = (0, util_1.promisify)(fs_1.unlink); class LocalService extends base_service_1.BaseService { constructor(options) { super(options); this.options = options; this.directoryService = new directory_service_1.DirectoryService(options); } async create(data, query = {}) { const { path: root = '' } = query; await this.directoryService.create({ name: root }); // Fullpath. const { directory: folder } = this.options; const fullpath = path_1.default.resolve(folder, root, data.name); return new Promise((resolve, reject) => { const writable = (0, fs_1.createWriteStream)(fullpath); writable.on('finish', async () => { const data = await this.get(fullpath); resolve(data); }); writable.on('error', (err) => reject(err)); data.stream.pipe(writable); }); } async list(query = {}) { const { pagination, directory } = this.options; const { size, page, path: root = '' } = query; const dir = path_1.default.resolve(`${directory}/${root}`); const isExist = await this.hasExist(dir); if (!isExist) return (0, helpers_1.paginate)([], 0); const items = await readdirAsync(dir); const filtered = items.filter((item) => { const stat = (0, fs_1.statSync)(`${dir}/${item}`); return stat.isFile(); }); const length = pagination.max >= size ? size : pagination.default; const paginatedItems = (0, helpers_1.paginate)(filtered, length, page); const files = await Promise.all(paginatedItems.items.map((item) => this.get(`${dir}/${item}`))); return Object.defineProperty(paginatedItems, 'items', { value: files }); } async get(id, query = {}) { const fullpath = this.resolvePath(id); const isExist = await this.hasExist(fullpath); if (!isExist) throw new http_errors_1.NotFound('File does not exist'); return this.builder(fullpath); } async remove(id, query = {}) { const fullpath = this.resolvePath(id); // Get file before remove. const file = await this.get(id); await unlinkAsync(fullpath); return file; } } exports.LocalService = LocalService; //# sourceMappingURL=service.js.map