@filesrocket/local
Version:
Filesrocket service that manages your files locally
66 lines • 2.37 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseService = void 0;
const fs_1 = require("fs");
const util_1 = require("util");
const path_1 = __importDefault(require("path"));
const statAsync = (0, util_1.promisify)(fs_1.stat);
class BaseService {
constructor(options) {
this.options = options;
}
/**
* Method responsible for constructing the entities (Files)
* @param root Path
*/
async builder(root) {
const fullpath = path_1.default.resolve(root);
const { directory: folder, host } = this.options;
const { base: name, ext, dir } = path_1.default.parse(fullpath);
const regex = new RegExp(`${folder}.+`, 'g');
const [directory] = dir.match(regex) || [folder];
const chunks = directory.split(path_1.default.sep);
const stat = await statAsync(fullpath);
const url = `${host}/${chunks.join('/')}/${name}`;
const items = chunks.slice(1, chunks.length);
stat.isDirectory() && items.push(name);
return {
id: url,
name,
ext,
url,
size: stat.size,
dir: items.join('/'),
createdAt: stat.birthtime,
updatedAt: stat.atime
};
}
/**
* Method responsible for parsing the HTTP URL to path
*
* For example: `http://domain.com/uploads/images/filesrocket.png` -> `uploads/images/filesrocket.png`
*
* @param root Path or URL
*/
resolvePath(root) {
const { directory } = this.options;
const regex = new RegExp(`${directory}.+`, 'g');
const [dir] = root.match(regex) || [''];
return path_1.default.resolve(dir);
}
/**
* Responsible method if entity exists (Files or Directories)
* @param root Path
*/
async hasExist(root) {
return new Promise((resolve) => {
const fullpath = path_1.default.resolve(root);
(0, fs_1.access)(fullpath, (err) => (err ? resolve(false) : resolve(true)));
});
}
}
exports.BaseService = BaseService;
//# sourceMappingURL=base.service.js.map