UNPKG

@filesrocket/local

Version:

Filesrocket service that manages your files locally

67 lines 2.84 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DirectoryService = void 0; const http_errors_1 = require("http-errors"); const fs_1 = require("fs"); const util_1 = require("util"); const path_1 = __importDefault(require("path")); const base_service_1 = require("./base.service"); const helpers_1 = require("../helpers"); const readdirAsync = (0, util_1.promisify)(fs_1.readdir); const mkdirAsync = (0, util_1.promisify)(fs_1.mkdir); const rmdirAsync = (0, util_1.promisify)(fs_1.rmdir); class DirectoryService extends base_service_1.BaseService { constructor(options) { super(options); this.options = options; } async create(data) { const { directory } = this.options; const root = path_1.default.resolve(`${directory}/${data.name}`); const isExist = await this.hasExist(root); if (isExist) return this.builder(root); const fullpath = await mkdirAsync(root, { recursive: true }); if (!fullpath) { throw new http_errors_1.InternalServerError('An error occurred while performing this operation'); } return this.get(root); } async list(query = {}) { const { directory, pagination } = this.options; const { size, page, path: root = '' } = query; const length = pagination.max >= size ? size : pagination.default; const fullpath = path_1.default.resolve(`${directory}/${root}`); const items = await readdirAsync(fullpath); const filtered = items.filter((item) => { const data = (0, fs_1.statSync)(`${fullpath}/${item}`); return data.isDirectory(); }); const itemsPaginated = (0, helpers_1.paginate)(filtered, length, page); const directories = await Promise.all(itemsPaginated.items.map((item) => { const root = path_1.default.resolve(`${fullpath}/${item}`); return this.get(root); })); return Object.defineProperty(itemsPaginated, 'items', { value: directories }); } async get(id, query = {}) { const fullpath = this.resolvePath(id); const isExist = await this.hasExist(fullpath); if (!isExist) throw new http_errors_1.NotFound('Directory does not exist'); return this.builder(fullpath); } async remove(root) { const fullpath = this.resolvePath(root); const entity = await this.get(fullpath); await rmdirAsync(fullpath); return entity; } } exports.DirectoryService = DirectoryService; //# sourceMappingURL=directory.service.js.map