Socket
Socket
Sign inDemoInstall

utils-google-drive

Package Overview
Dependencies
55
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.3 to 2.0.0

CHANGELOG.md

60

index.js

@@ -11,6 +11,11 @@ #!/usr/bin/env node

/**
* Base class for utils-google-drive errors
* which have the name UtilsGDriveError
*/
class UtilsGDriveError extends Error {
/* eslint-disable-next-line require-jsdoc */
constructor(args) {
super(args);
this.name = "UtilsGDriveError"
this.name = 'UtilsGDriveError';
}

@@ -23,28 +28,35 @@ };

*/
class utilsGDrive {
api = drive._addDrive(utils.api, this);
_resolveParamsId = utils._resolveParamsId;
_resolveFId = utils._resolveFId;
listFiles = utils.listFiles;
getFiles = utils.getFiles;
updateFiles = utils.updateFiles;
getFileId = utils.getFileId;
getFileName = utils.getFileName;
getMime = utils.getMime;
listChildren = utils.listChildren;
download = drive._addDrive(download.download, this);
_downloadFile = download._downloadFile;
_overwrite = upload._overwrite;
class UtilsGDrive {
/* eslint-disable-next-line require-jsdoc */
constructor() {
/* eslint-disable no-multi-spaces */
this.api = drive._addDrive(utils.api, this),
this.listFiles = utils.listFiles;
this.getFiles = utils.getFiles;
this.updateFiles = utils.updateFiles;
this.getFileId = utils.getFileId;
this.getFileName = utils.getFileName;
this.getMime = utils.getMime;
this.listChildren = utils.listChildren;
this.download = drive._addDrive(download.download, this);
this._downloadFile = download._downloadFile;
this._overwrite = upload._overwrite;
makeFolder = upload.makeFolder;
makeFolder = upload.makeFolder;
upload = upload.upload;
_uploadFile = upload._uploadFile;
this.makeFolder = upload.makeFolder;
this.makeFolder = upload.makeFolder;
this.upload = upload.upload;
this._uploadFile = upload._uploadFile;
del = del.del;
rename = update.rename;
move = update.move;
Error = UtilsGDriveError;
this.del = del.del;
this.rename = update.rename;
this.move = update.move;
this.Error = UtilsGDriveError;
this._resolveId = utils._resolveId;
this._resolveIdFromString = utils._resolveIdFromString;
this._handleListFilesResponse = utils._handleListFilesResponse;
/* eslint-enable no-multi-spaces */
};
};
module.exports = new utilsGDrive();
module.exports = new UtilsGDrive();

7

lib/delete.js

@@ -9,6 +9,7 @@ 'use strict';

* Deletes a file or folder in Google drive.
* @param {Object|string} identifiers - An object
* @param {Object|string} identifiers - An object
* used to identify a file or folder. Must have either
* <code>fileId</code> or <code>fileName</code>.
* This parameter also accepts a string containing the file/folder id.
* Also accepts a string containing the file/folder
* id or path (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileId - File/folder id

@@ -32,3 +33,3 @@ * @param {string} identifiers.fileName - File/folder name

try {
const fileId = await this._resolveFId(identifiers);
const fileId = await this._resolveId(identifiers);
responseData = await this.api('files', 'delete', {fileId});

@@ -35,0 +36,0 @@ } catch (err) {

@@ -13,6 +13,7 @@ 'use strict';

* Downloads a file or folder from Google Drive.
* @param {Object|string} identifiers - An object
* @param {Object|string} identifiers - An object
* used to identify a file or folder. Must have either
* <code>fileId</code> or <code>fileName</code>.
* This parameter also accepts a string containing the file/folder id.
* Also accepts a string containing the file/folder
* id or path (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileId - File/folder id

@@ -38,3 +39,3 @@ * @param {string} identifiers.fileName - File/folder name

try {
fileId = await this._resolveFId(identifiers);
fileId = await this._resolveId(identifiers);
} catch (err) {

@@ -69,5 +70,3 @@ return console.error(err);

} catch (err) {
const d = new Date();
if (err.code === 'EEXIST') fs.utimesSync(out, d, d);
else return console.error(err);
return console.error(err);
}

@@ -74,0 +73,0 @@ const children = await this.listChildren({fileId});

@@ -10,6 +10,7 @@ 'use strict';

* Renames a file or folder in Google Drive.
* @param {Object|string} identifiers - An object
* @param {Object|string} identifiers - An object
* used to identify a file or folder. Must have either
* <code>fileId</code> or <code>fileName</code>.
* This parameter also accepts a string containing the file/folder id.
* Also accepts a string containing the file/folder
* id or path (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileId - File/folder id

@@ -28,3 +29,3 @@ * @param {string} identifiers.fileName - File/folder name

try {
fileId = await this._resolveFId(identifiers);
fileId = await this._resolveId(identifiers);
} catch (err) {

@@ -39,6 +40,7 @@ return console.error(err);

* Moves a file or folder in Google Drive.
* @param {Object|string} identifiers - An object
* @param {Object|string} identifiers - An object
* used to identify a file or folder. Must have either
* <code>fileId</code> or <code>fileName</code>.
* This parameter also accepts a string containing the file/folder id.
* Also accepts a string containing the file/folder
* id or path (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileId - File/folder id

@@ -48,7 +50,5 @@ * @param {string} identifiers.fileName - File/folder name

* @param {string} [identifiers.parentName] - Parent name
* @param {Object|string} [newParentParams] - An object identifying
* the new parent. Can also be a string containing the parent id.
* @param {Object|string} [newParentIdentifiers] - The same as
* <code>identifiers</code> but for the new parent.
* File will be moved to root folder if this parameter isn't specified.
* @param {string} [newParentParams.newParentId] - Id of new parent
* @param {string} [newParentParams.newParentName] - Name of new parent
* @return {undefined} None

@@ -61,4 +61,7 @@ * @example

* utilsGDrive.move("fileId", "folderId");
*
* // move a file using paths
* utilsGDrive.move("path/to/file", "path/to/newParent");
*/
async function move(identifiers, newParentParams = {}) {
async function move(identifiers, newParentIdentifiers) {
let fileId;

@@ -68,6 +71,6 @@ let oldParentId;

try {
fileId = await this._resolveFId(identifiers);
fileId = await this._resolveId(identifiers);
const responseData = await this.getFiles({fileId, fields: 'parents'});
oldParentId = responseData.parents[0];
newParentId = await this._resolveParamsId(newParentParams);
newParentId = await this._resolveId(newParentIdentifiers);
} catch (err) {

@@ -74,0 +77,0 @@ return console.error(err);

@@ -46,7 +46,4 @@ 'use strict';

async function _overwrite({name, mimeType, parents}) {
const q =
'name="' + name +
'" and mimeType="' + mimeType +
'" and "' + parents[0] +
'" in parents and trashed=false';
const q = `name='${name}' and mimeType='${mimeType}'` +
` and '${parents[0]}' in parents and trashed=false`;
const data = await this.listFiles({q: q});

@@ -66,8 +63,8 @@ if (data) {

* A string containing the name of the folder to be created may be passed
* instead. In this case, the folder will be created at the root folder.
* instead. In this case, the folder will be created at the root folder
* @param {string} params.folderName - Name of folder to be created
* @param {string} [params.parentId] - Id of parent folder
* where the folder should be created
* @param {string} [params.parentName] - Name of parent folder
* where the folder should be created
* @param {Object} [params.parentIdentifiers] - Same as
* <code>identifiers</code> in other methods
* (e.g. {@link getMime}) but for the parent folder where the
* new folder will be created
* @param {boolean} [params.overwrite] - Whether to overwrite

@@ -83,6 +80,10 @@ * an existing folder. Default value is <code>false</code>

*
* // make a new folder name "newFolder" in the root folder
* // make a new folder named "newFolder" in the root folder
* utilsGDrive.makeFolder("newFolder");
*/
async function makeFolder({folderName, parentId, parentName, overwrite=false}) {
async function makeFolder({
folderName,
parentIdentifiers = {},
overwrite=false,
}) {
if (typeof(arguments[0]) === 'string') {

@@ -97,6 +98,5 @@ folderName = arguments[0];

let responseData;
try {
parentId = await this._resolveParamsId({parentId, parentName});
const parentId = await this._resolveId(parentIdentifiers);
fileMetadata.parents = [parentId];

@@ -120,8 +120,8 @@ if (overwrite) this._overwrite(fileMetadata);

* A string containing the path to the file/folder to be uploaded may be passed
* instead. In this case, the file/folder will be uploaded at the root folder.
* instead. In this case, the file/folder will be uploaded at the root folder
* @param {string} params.localPath - Path to file or folder on disk
* @param {string} [params.parentId] - Id of parent folder
* where the file/folder should be uploaded
* @param {string} [params.parentName] - Name of parent folder
* where the file/folder should be uploaded
* @param {Object} [params.parentIdentifiers] - Same as
* <code>identifiers</code> in other methods
* (e.g. {@link getMime}) but for the parent folder
* where the file/folder is to be uploaded to
* @param {boolean} [params.overwrite] - Whether to overwrite

@@ -140,3 +140,9 @@ * existing files/folders. Default value is <code>false</code>

*/
async function upload({localPath, parentId, parentName, overwrite=false}) {
async function upload({
localPath,
parentIdentifiers = {},
overwrite=false,
}) {
// handle string
let parentId;
if (typeof(arguments[0]) === 'string') {

@@ -150,4 +156,5 @@ localPath = arguments[0];

// parent id
try {
parentId = await this._resolveParamsId({parentId, parentName});
parentId = await this._resolveId(parentIdentifiers);
} catch (err) {

@@ -157,2 +164,3 @@ return console.error(err);

// MIME type
let mimeType;

@@ -165,2 +173,3 @@ if (isDir) {

// metadata
const fileMetadata = {

@@ -173,2 +182,3 @@ name: fileName,

let fileId;
// handle directories

@@ -180,3 +190,3 @@ if (isDir) {

folderName: fileName,
parentId,
parentIdentifiers: parentId,
overwrite,

@@ -193,7 +203,8 @@ });

localPath: localPathChild,
parentId: parentIdChildren,
parentIdentifiers: parentIdChildren,
overwrite,
});
}
// handle files
// handle files
} else {

@@ -203,2 +214,3 @@ if (overwrite) this._overwrite(fileMetadata);

}
return fileId;

@@ -205,0 +217,0 @@ }

'use strict';
const path = require('path');
module.exports = {

@@ -8,8 +10,9 @@ api,

updateFiles,
getFileName,
getFileId,
getFileName,
_resolveIdFromString,
_resolveId,
_handleListFilesResponse,
getMime,
listChildren,
_resolveParamsId,
_resolveFId,
};

@@ -76,3 +79,4 @@

}
return this.api('files', 'list', params).catch((err) => console.error(err));
return this.api('files', 'list', params)
.catch((err) => console.error(err));
}

@@ -104,3 +108,4 @@

if (!params.fields) params.fields = 'name, id, mimeType';
return this.api('files', 'get', params).catch((err) => console.error(err));
return this.api('files', 'get', params)
.catch((err) => console.error(err));
}

@@ -133,32 +138,66 @@

}
return this.api('files', 'update', params).catch((err) => console.error(err));
return this.api('files', 'update', params)
.catch((err) => console.error(err));
}
/**
* Resolves id of file/folder using <code>params</code>.
* @param {Object|string} params - An object having a property whose name
* ends in either "Name" or "Id". Can also be a string containing the
* the file/folder id
* Gets file/folder name given id.
* @param {string} fileId - File/folder id
* @return {string} File/folder name
* @example
* // get name of file whose id is "fileId"
* utilsGDrive.getFileName("fileId");
*/
async function getFileName(fileId) {
const responseData = await this.getFiles({fileId, fields: 'name'});
if (responseData) return responseData.name;
}
/**
* Verifies that exactly one file was found
* in Google Drive matching the identifiers.
* @see Called by <code>getFileId</code>
* @param {Object} responseData - Response data from
* <code>listFiles</code>
* @param {string} fileName - <code>fileName</code>
* from <code>getFileId</code>
* @return {undefined|UtilsGDriveError} <code>undefined</code>
* if only 1 file found. <code>UtilsGDriveError</code>
* if 0 or more than 1 file found
* @access private
*/
function _handleListFilesResponse(responseData, fileName) {
const nFiles = responseData.length;
let e;
if (nFiles === 0) {
e = new this.Error('No files found matching identifiers specified.');
} else if (nFiles > 1) {
e = new this.Error(
`Multiple files found: ${fileName}. Consider specifying parent.`);
}
return e;
}
/**
* Resolves file id from string.
* @param {string} str - Can be either file id
* or path
* @return {string} File/folder id
* @access private
*/
async function _resolveParamsId(params) {
if (typeof params === 'string') return params;
let propPrefix;
for (const key in params) {
if (key.indexOf('Name') + key.indexOf('Id') > -2) {
propPrefix = key.replace('Id', '').replace('Name', '');
break;
}
async function _resolveIdFromString(str) {
const names = str.split(path.sep);
if (names.length === 1) {
return names[0];
}
// id given
if (params[propPrefix + 'Id']) {
return params[propPrefix + 'Id'];
// name given
} else if (params[propPrefix + 'Name']) {
return this.getFileId(params[propPrefix + 'Name']);
// default to root if neither id nor name given
} else {
return 'root';
let currentId = await this.getFileId({
fileName: names[0],
});
for (const name of names.slice(1)) {
currentId = await this.getFileId({
fileName: name,
parentId: currentId,
});
}
return currentId;
}

@@ -168,4 +207,7 @@

* Gets file/folder id given name.
* @param {Object|string} identifiers - Function parameters.
* A string containing the file/folder name may be passed instead.
* @param {Object|string} identifiers - An object
* used to identify a file or folder. Must have
* <code>fileName</code>. Also accepts
* a string containing the file/folder name or path
* (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileName - File/folder name

@@ -185,2 +227,5 @@ * @param {string} [identifiers.parentId] - Parent id

*
* // code above is equivalent to the following
* utilsGDrve.getFileId("folderName/fileName");
*
* // get id of file whose name is "fileName"

@@ -190,12 +235,33 @@ * // assuming no other files/folders in Google Drive

* utilsGDrive.getFileId("fileName");
*
*/
async function getFileId({fileName, parentId, parentName}) {
// handle string
if (typeof(arguments[0]) === 'string') {
fileName = arguments[0];
if (arguments[0].indexOf(path.sep) + 1) {
return this._resolveIdFromString(arguments[0]);
} else {
fileName = arguments[0];
}
}
// build q
let q = 'name="' + fileName + '"';
if (parentId || parentName) {
parentId = await this._resolveParamsId({parentId, parentName});
q += ' and "' + parentId + '" in parents';
let p;
if (parentId) {
p = parentId;
} else if (parentName) {
const responseData = await this.listFiles({
q: 'name="' + parentName + '"',
fields: 'files(id)',
});
if (responseData) {
const files = responseData.files;
const e = this._handleListFilesResponse(files, fileName);
if (e) return console.error(e);
p = files[0].id;
}
}
q += ' and "' + p + '" in parents';
}

@@ -205,13 +271,6 @@

if (responseData) {
let e;
const nFiles = responseData.files.length;
if (nFiles > 1) {
e = new this.Error('Multiple files found: '+
fileName+
'. Consider specifying parent.');
} else if (nFiles === 0) {
e = new this.Error('No files found matching identifiers specified.');
}
const files = responseData.files;
const e = this._handleListFilesResponse(files, fileName);
if (e) return console.error(e);
return responseData.files[0].id;
return files[0].id;
}

@@ -221,15 +280,2 @@ }

/**
* Gets file/folder name given id.
* @param {string} fileId - File/folder id
* @return {string} File/folder name
* @example
* // get name of file whose id is "fileId"
* utilsGDrive.getFileName("fileId");
*/
async function getFileName(fileId) {
const responseData = await this.getFiles({fileId, fields: 'name'});
if (responseData) return responseData.name;
}
/**
* Resolves file/folder id given object with data

@@ -240,3 +286,4 @@ * identifying the file/folder.

* <code>fileId</code> or <code>fileName</code>.
* This parameter also accepts a string containing the file/folder id.
* Also accepts a string containing the file/folder
* id or path (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileId - File/folder id

@@ -251,28 +298,22 @@ * @param {string} identifiers.fileName - File/folder name

*/
async function _resolveFId(identifiers) {
if (typeof identifiers === 'string') return identifiers;
async function _resolveId(identifiers) {
// handle string
if (typeof(identifiers) === 'string') {
return this._resolveIdFromString(identifiers);
}
// pass fileId through if already specified
if (identifiers.fileId) return identifiers.fileId;
if (identifiers.folderId) return identifiers.folderId;
const fIdentifiers = ['fileId', 'fileName'];
const pIdentifiers = ['parentId', 'parentName'];
const fParams = {};
const pParams = {};
for (const key in identifiers) {
if (fIdentifiers.includes(key)) {
fParams[key] = identifiers[key];
} else if (pIdentifiers.includes(key)) {
pParams[key] = identifiers[key];
} else {
throw new this.Error('Invalid property name: ' + key);
// default to root if empty object
if (!Object.keys(identifiers).length) return 'root';
// validate identifiers
const validIdentifiers = ['fileId', 'fileName', 'parentId', 'parentName'];
for (const identifier in identifiers) {
if (validIdentifiers.indexOf(identifier) == -1) {
throw new this.Error('Invalid property name: ' + identifier);
}
}
let fName;
if (fParams.fileName) fName = fParams.fileName;
let parentId;
if (Object.keys(pParams).length) {
parentId = await this._resolveParamsId(pParams);
}
return this.getFileId({fileName: fName, parentId});
return this.getFileId(identifiers);
}

@@ -285,3 +326,4 @@

* <code>fileId</code> or <code>fileName</code>.
* This parameter also accepts a string containing the file/folder id.
* Also accepts a string containing the file/folder
* id or path (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileId - File/folder id

@@ -296,6 +338,9 @@ * @param {string} identifiers.fileName - File/folder name

*
* // get MIME type of file whose id is "fileId"
* // get MIME type of file using path
* utilsGDrive.getMime("parentName1/parentName2/fileName");
*
* // get MIME type of file whose fileName is "fileName"
* // and that resides in folder whose id is "folderId"
* utilsGDrive.getMime({
* fileId: "fileId",
* fileName: "fileName",
* parentId: "folderId"

@@ -307,3 +352,3 @@ * });

try {
fileId = await this._resolveFId(identifiers);
fileId = await this._resolveId(identifiers);
} catch (err) {

@@ -324,3 +369,4 @@ return console.error(err);

* <code>fileId</code> or <code>fileName</code>.
* This parameter also accepts a string containing the file/folder id.
* Also accepts a string containing the file/folder
* id or path (can be partial) to the file/folder in Google Drive.
* @param {string} identifiers.fileId - File/folder id

@@ -331,3 +377,3 @@ * @param {string} identifiers.fileName - File/folder name

* @param {string} [fields] - Data fields to request.
* Should follow the pattern <code>"files(fiel1, field2,...)"</code>.
* Should follow the pattern <code>"files(field1, field2,...)"</code>.
* Default value is <code>"files(name, id, mimeType)"</code>

@@ -341,9 +387,4 @@ * @return {Array} Each entry in the array returned

*
* // get ids of files in the folder whose name is "folderName"
* // and whose parent has the id "parentId"
* utilsGDrive.listChildren({
* fileName: "folderName",
* parentId: "parentId"
* }, "files(id)");
*
* // get ids of files in "folderName" using path
* utilsGDrive.listChildren("parentName1/parentName2/folderName", "files(id)");
*/

@@ -353,6 +394,7 @@ async function listChildren(identifiers, fields = 'files(name, id, mimeType)') {

try {
folderId = await this._resolveFId(identifiers);
folderId = await this._resolveId(identifiers);
} catch (err) {
return console.error(err);
}
const listFilesParams = {

@@ -359,0 +401,0 @@ q: '"' + folderId + '" in parents',

{
"name": "utils-google-drive",
"version": "1.0.3",
"version": "2.0.0",
"description": "A simple and flexible package for interacting with Google Drive",

@@ -11,2 +11,3 @@ "main": "index.js",

"test": "mocha",
"coverage": "nyc npm run test",
"lint": "eslint lib test",

@@ -38,4 +39,6 @@ "lint:fix": "eslint lib test --fix",

"eslint-config-google": "^0.14.0",
"fs-extra": "^9.0.1"
"fs-extra": "^9.0.1",
"mocha": "^8.0.1",
"nyc": "^15.1.0"
}
}
# **utils-google-drive**
[![Build Status](https://travis-ci.com/curtcommander/utils-google-drive.svg?branch=master)](https://travis-ci.com/curtcommander/utils-google-drive)
[![npm version](https://badge.fury.io/js/utils-google-drive.svg)](https://www.npmjs.com/package/utils-google-drive)

@@ -18,8 +19,9 @@ [![repo](https://img.shields.io/badge/repo-gray.svg)](https://github.com/curtcommander/utils-google-drive)

## **Flexible file/folder specification**
utils-google-drive allows files and folders in Google Drive to be specified by either name or id.
Information on the parent folder can and many times should also be included.
For example, specifying a parent will resolve the ambiguity
of trying to access a file or folder by name when there are multiple files/folders in Google Drive with that name.
utils-google-drive allows files and folders in Google Drive to be specified by either name or id. Information on the parent folder can and many times should also be included. Specifying a parent will resolve the ambiguity of trying to access a file or folder by name when there are multiple files/folders in Google Drive with that name.
Objects with the properties `fileId`/`folderId`, `fileName`/`folderName`, `parentId`, and `parentName` are generally used to specify a file or folder and are passed as arguments to utils-google-drive methods. For convenience, a string containing the file/folder id may also be passed instead. Consult the [docs](https://curtcommander.github.io/utils-google-drive/) for details on the arguments that each method accepts.
Objects with the properties `fileId`, `fileName`, `parentId`, and `parentName` are generally used to specify a file or folder and are passed as arguments to utils-google-drive methods. For convenience, a string containing the file/folder id or path to the file or folder in Google Drive may be passed instead.
If specifying a path, partial paths can be used and are encouraged. Ideally, you would specify a partial path that contains just enough information to uniquely identify the file in Google Drive. For example, suppose you wanted to download the file "annualReport.pdf" in the folder "reports2020". If there are multiple files named "annualReport.pdf" in Google Drive but no other folders with the name "reports2020", you could use the partial path `"reports2020/annualReport.pdf"` to identify the file of interest. This path is preferable to a longer one because it finds the file quicker, jumping in at the uniquely-named folder "reports2020" and not worrying itself with folders higher up the chain.
There is some variation in how to specify a file or folder across utils-google-drive methods. Consult the [docs](https://curtcommander.github.io/utils-google-drive/) for details.

@@ -54,5 +56,4 @@ ## **Examples**

// move folder "reports" in Google Drive to root folder
// "root" is special API keyword
utilsGDrive.move({fileName: "reports"}, {newParentId: "root"});
// move folder "reports2020" to the folder "reports"
utilsGDrive.move("path/to/reports2020", "path/to/reports");

@@ -59,0 +60,0 @@ // delete file with id "fileId"

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc