UNPKG

backendless-console-sdk

Version:

Backendless Console SDK for Node.js and browser

365 lines (350 loc) 23 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _urls = _interopRequireDefault(require("./urls")); var _totalRows = _interopRequireDefault(require("./utils/total-rows")); var _cacheTags = require("./utils/cache-tags"); var _path = require("./utils/path"); var _baseService = _interopRequireDefault(require("./base/base-service")); function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = (0, _getPrototypeOf2["default"])(t); if (r) { var s = (0, _getPrototypeOf2["default"])(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return (0, _possibleConstructorReturn2["default"])(this, e); }; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /* eslint-disable max-len */ var getFileFolder = function getFileFolder(file) { var tokens = file.split('/'); if (tokens.length > 1) { tokens.pop(); return tokens.join('/'); } return ''; }; var Files = /*#__PURE__*/function (_BaseService) { (0, _inherits2["default"])(Files, _BaseService); var _super = _createSuper(Files); function Files(req) { var _this; (0, _classCallCheck2["default"])(this, Files); _this = _super.call(this, req); _this.serviceName = 'files'; return _this; } /** * @typedef {Object} loadDirectory__params * @paramDef {"type":"string","label":"Pattern","name":"pattern","description":"Optional search pattern to filter files and directories by name","required":false} * @paramDef {"type":"boolean","label":"Sub","name":"sub","description":"Whether to include subdirectories in the search","required":false} * @paramDef {"type":"string","label":"Sort By","name":"sortBy","description":"Field to sort results by (e.g., 'name', 'size', 'modified')","required":false} * @paramDef {"type":"string","label":"Sort Direction","name":"sortDirection","description":"Sort direction: 'asc' for ascending, 'desc' for descending","required":false} * @paramDef {"type":"number","label":"Page Size","name":"pageSize","description":"Number of items to return per page for pagination","required":false} * @paramDef {"type":"number","label":"Offset","name":"offset","description":"Number of items to skip for pagination","required":false} */ /** * @aiToolName Load Directory * @category Data * @description Loads the contents of a directory with optional filtering, sorting and pagination support. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"path","label":"Path","description":"The directory path to load. If not specified, root path will be used","required":false} * @paramDef {"type":"loadDirectory__params","name":"params","label":"Parameters","description":"Optional parameters for filtering, sorting and pagination","required":false} * @sampleResult {"data":[{"name":"documents","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/documents","url":"documents"},{"name":"config.json","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/config.json","size":1024,"url":"config.json"}],"totalRows":2} */ (0, _createClass2["default"])(Files, [{ key: "loadDirectory", value: function loadDirectory(appId, path, params) { path = path || '/'; var _ref = params || {}, pattern = _ref.pattern, sub = _ref.sub, sortBy = _ref.sortBy, sortDirection = _ref.sortDirection, pageSize = _ref.pageSize, offset = _ref.offset; var dataReq = this.req.get(_urls["default"].directoryView(appId, path)).query({ pattern: pattern, sub: sub, sortBy: sortBy, sortDirection: sortDirection, pageSize: pageSize, offset: offset }).cacheTags((0, _cacheTags.FOLDER)(appId, path)); return (0, _totalRows["default"])(this.req).getWithData(dataReq); } /** * @typedef {Object} loadFullDirectory__params * @paramDef {"type":"string","label":"Pattern","name":"pattern","description":"Optional search pattern to filter files and directories by name","required":false} * @paramDef {"type":"boolean","label":"Sub","name":"sub","description":"Whether to include subdirectories in the search","required":false} * @paramDef {"type":"string","label":"Sort By","name":"sortBy","description":"Field to sort results by (e.g., 'name', 'size', 'modified')","required":false} * @paramDef {"type":"string","label":"Sort Direction","name":"sortDirection","description":"Sort direction: 'asc' for ascending, 'desc' for descending","required":false} */ /** * @aiToolName Load Full Directory * @category Data * @description Loads the complete contents of a directory by automatically paginating through all results. Unlike loadDirectory, this method returns all items without pagination limits. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"path","label":"Path","description":"The directory path to load completely. If not specified, root path will be used","required":false} * @paramDef {"type":"loadFullDirectory__params","name":"params","label":"Parameters","description":"Optional parameters for filtering and sorting (pagination handled automatically)","required":false} * @sampleResult [{"name":"documents","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/documents","url":"documents"},{"name":"config.json","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/config.json","size":1024,"url":"config.json"}] */ }, { key: "loadFullDirectory", value: (function () { var _loadFullDirectory = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee(appId, path, params) { var currentQuery, url, totalCount, filesList, requests, results; return _regenerator["default"].wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: currentQuery = _objectSpread(_objectSpread({}, params), {}, { pageSize: 100, offset: 0 }); url = _urls["default"].directoryView(appId, path); _context.next = 4; return (0, _totalRows["default"])(this.req).get(url); case 4: totalCount = _context.sent; filesList = []; requests = []; while (currentQuery.offset < totalCount) { requests.push(this.req.get(url).query(currentQuery)); currentQuery = _objectSpread(_objectSpread({}, currentQuery), {}, { offset: currentQuery.offset + 100 }); } _context.next = 10; return Promise.all(requests); case 10: results = _context.sent; results.forEach(function (files) { return filesList.push.apply(filesList, (0, _toConsumableArray2["default"])(files)); }); return _context.abrupt("return", filesList); case 13: case "end": return _context.stop(); } }, _callee, this); })); function loadFullDirectory(_x, _x2, _x3) { return _loadFullDirectory.apply(this, arguments); } return loadFullDirectory; }() /** * @aiToolName Create Directory * @category Data * @description Creates a new directory in the specified path. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"path","label":"Path","description":"The path where the directory will be created. If not specified, root path will be used","required":false} * @paramDef {"type":"string","name":"folderName","label":"Folder Name","description":"The name of the directory to be created","required":true} * @sampleResult {"name":"documents","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/documents","url":"documents"} */ ) }, { key: "createDir", value: function createDir(appId, path, folderName) { return this.req.post(_urls["default"].createDir(appId, path, folderName)).cacheTags((0, _cacheTags.FOLDER)(appId, path)); } /** * @aiToolName Get File Content * @category Data * @description Downloads and returns the content of a specified file. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"File Path","description":"The path to the file within the application","required":true} * @sampleResult "This is the content of the file" */ }, { key: "getFileContent", value: (function () { var _getFileContent = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee2(appId, filePath) { return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: return _context2.abrupt("return", this.req.get(_urls["default"].fileDownload(appId, filePath))); case 1: case "end": return _context2.stop(); } }, _callee2, this); })); function getFileContent(_x4, _x5) { return _getFileContent.apply(this, arguments); } return getFileContent; }() /** * @aiToolName Perform File Operation * @category Data * @description Performs file operations such as compressing directories into ZIP archives or extracting ZIP files. * For root directory operations, the path should be '/' or empty. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"File Path","description":"The path to the file or directory to operate on. Use '/' for root directory operations","required":true} * @paramDef {"type":"string","name":"operation","label":"Operation","description":"The operation to perform. Valid values: 'zip' (compress directory) or 'unzip' (extract archive)","required":true} * @sampleResult "Operation started successfully. You will receive an email notification when complete." */ ) }, { key: "performOperation", value: function performOperation(appId, filePath, operation) { //for root directory operations it has send '/' as path var path = filePath ? (0, _path.encodePath)(filePath) : encodeURIComponent('/'); return this.req.put("".concat(_urls["default"].appConsole(appId), "/files/").concat(path)).query({ operation: operation }).cacheTags((0, _cacheTags.FOLDER)(appId, getFileFolder(path))); } /** * @aiToolName Check File Exists * @category Data * @description Checks if a file exists at the specified path. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"File Path","description":"The path to check for file existence","required":true} * @sampleResult "true" */ }, { key: "fileExists", value: function fileExists(appId, filePath) { return this.req.get(_urls["default"].fileExists(appId, filePath)); } /** * @aiToolName Edit File * @category Data * @description Modifies the content of an existing file. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"File Path","description":"The path to the file to be edited","required":true} * @paramDef {"type":"string","name":"fileContent","label":"File Content","description":"The new content to be written to the file","required":true} * @sampleResult {"name":"example.txt","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/example.txt","size":1024,"url":"example.txt"} */ }, { key: "editFile", value: function editFile(appId, filePath, fileContent) { return this.req.post(_urls["default"].fileEdit(appId, filePath), { file: fileContent }); } /** * @aiToolName Create File * @category Data * @description Creates a new file with the specified content at the given path. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"File Path","description":"The path where the file will be created","required":true} * @paramDef {"type":"string","name":"fileContent","label":"File Content","description":"The content to be written to the new file","required":true} * @sampleResult {"name":"example.txt","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/example.txt","size":1024,"url":"example.txt"} */ }, { key: "createFile", value: function createFile(appId, filePath, fileContent) { return this.req.post(_urls["default"].fileCreate(appId, filePath), { file: fileContent }).set('Accept', '*/*') //workarround for BKNDLSS-13702 .cacheTags((0, _cacheTags.FOLDER)(appId, getFileFolder(filePath))); } /** * @aiToolName Move File * @category Data * @description Moves a file from one location to another within the application. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"Source File Path","description":"The current path of the file to be moved","required":true} * @paramDef {"type":"string","name":"newFilePath","label":"Destination File Path","description":"The new path where the file will be moved","required":true} * @sampleResult "https://your-server.com/your-app-id/your-api-key/files/destination/filename.txt" */ }, { key: "moveFile", value: function moveFile(appId, filePath, newFilePath) { return this.req.post(_urls["default"].fileMove(appId, filePath), (0, _path.encodePath)(newFilePath)).cacheTags((0, _cacheTags.FOLDER)(appId, getFileFolder(filePath))); } /** * @aiToolName Copy File * @category Data * @description Creates a copy of an existing file at a new location. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"Source File Path","description":"The path of the file to be copied","required":true} * @paramDef {"type":"string","name":"newFilePath","label":"Destination File Path","description":"The path where the copy will be created","required":true} * @sampleResult "https://your-server.com/your-app-id/your-api-key/files/destination/copy-filename.txt" */ }, { key: "copyFile", value: function copyFile(appId, filePath, newFilePath) { return this.req.post(_urls["default"].fileCopy(appId, filePath), (0, _path.encodePath)(newFilePath)).cacheTags((0, _cacheTags.FOLDER)(appId, getFileFolder(filePath))); } /** * @aiToolName Rename File * @category Data * @description Renames an existing file to a new name. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"File Path","description":"The path of the file to be renamed","required":true} * @paramDef {"type":"string","name":"newFileName","label":"New File Name","description":"The new name for the file (without path)","required":true} * @sampleResult "https://your-server.com/your-app-id/your-api-key/files/new-filename.txt" */ }, { key: "renameFile", value: function renameFile(appId, filePath, newFileName) { return this.req.post(_urls["default"].fileRename(appId, filePath), encodeURIComponent(newFileName)).cacheTags((0, _cacheTags.FOLDER)(appId, getFileFolder(filePath))); } /** * @aiToolName Delete File * @category Data * @description Permanently deletes a file from the application. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"filePath","label":"File Path","description":"The path of the file to be deleted","required":true} * @sampleResult "" */ }, { key: "deleteFile", value: function deleteFile(appId, filePath) { return this.req["delete"](_urls["default"].fileDelete(appId, filePath)).cacheTags((0, _cacheTags.FOLDER)(appId, getFileFolder(filePath))); } /** * @aiToolName Upload File * @category Data * @description Uploads a file to the specified path in the application storage. * The file must be sent as multipart/form-data. If a file with the same name exists, it can be optionally overwritten. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application where the file will be stored","required":true} * @paramDef {"type":"file","name":"file","label":"File","description":"The file to be uploaded (sent as multipart/form-data)","required":true} * @paramDef {"type":"string","name":"path","label":"Target Path","description":"The destination folder path where the file will be uploaded","required":true} * @paramDef {"type":"string","name":"fileName","label":"File Name","description":"The name under which the file will be saved","required":true} * @paramDef {"type":"boolean","name":"overwrite","label":"Overwrite Existing","description":"Whether to overwrite the file if one with the same name already exists (default: false)","required":false} * @sampleResult {"name":"uploaded-file.txt","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/uploads/uploaded-file.txt","size":2048,"url":"uploads/uploaded-file.txt"} */ }, { key: "uploadFile", value: function uploadFile(appId, file, path, fileName) { var overwrite = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; return this.req.post(_urls["default"].fileUpload(appId, "".concat(path, "/").concat(fileName)), file).query({ overwrite: overwrite }).cacheTags((0, _cacheTags.FOLDER)(appId, path)); } }, { key: "createConsoleFile", value: function createConsoleFile(appId, path, content) { return this.req.post("".concat(_urls["default"].appConsole(appId), "/files/create/").concat((0, _path.encodePath)(path)), content).set('Accept', '*/*') //workarround for BKNDLSS-13702 .cacheTags((0, _cacheTags.FOLDER)(appId, getFileFolder(path))); } /** * @aiToolName View Files * @category Data * @description Retrieves a view of files and directories for browsing purposes. * @paramDef {"type":"string","name":"appId","label":"Application ID","description":"The identifier of the application","required":true} * @paramDef {"type":"string","name":"path","label":"Path","description":"The directory path to view. Defaults to root if not specified","required":false} * @sampleResult [{"name":"documents","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/documents","url":"documents"},{"name":"config.json","createdOn":1609459200000,"updatedOn":1609459200000,"publicUrl":"https://your-server.com/your-app-id/your-api-key/files/config.json","size":1024,"url":"config.json"}] */ }, { key: "viewFiles", value: function viewFiles(appId) { var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; return this.req.get(_urls["default"].fileView(appId, path)); } }]); return Files; }(_baseService["default"]); var _default = exports["default"] = function _default(req) { return Files.create(req); };