Skip to content

Commit

Permalink
fix: eslint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
d0whc3r committed Jul 5, 2020
1 parent 3a80e76 commit 38657a7
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 39 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ module.exports = {
{
files: ['**/*.e2e.ts', '**/*.spec.ts'],
rules: {
'sonarjs/no-duplicate-string': 0
'sonarjs/no-duplicate-string': 0,
'sonarjs/cognitive-complexity': 0
},
env: {
jest: true
Expand Down
2 changes: 1 addition & 1 deletion cli/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Cli } from './climodule';

(async () => {
void (async () => {
await new Cli().parseOptions();
})();
1 change: 1 addition & 0 deletions cli/cliconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ let options: GDriveOptions = {};
try {
options = commandLineArgs(optionDefinitions);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
console.error('[-] Error:', e.message);
process.exit(1);
}
Expand Down
10 changes: 7 additions & 3 deletions cli/climodule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class Cli {
async parseOptions() {
for (const command in this.opts) {
if (Object.prototype.hasOwnProperty.call(this.opts, command)) {
const args = this.opts[command];
const args = this.opts[command] as string | string[];
const zip = this.opts['zip'];
const folder = this.opts['folder'];
const replace = this.opts['replace'];
Expand Down Expand Up @@ -96,7 +96,9 @@ export class Cli {
try {
mysqlfile = await this.createDumpFile();
} catch (err) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/restrict-template-expressions
console.error(colors.bold[theme.error](`${Config.TAG} Error mysql ${err}`));
process.exit(-1);
}
Expand Down Expand Up @@ -143,7 +145,7 @@ export class Cli {
parsed.forEach((file) => {
const fileName = file.isFolder ? this.showFolder(file.name) : file.name;
const parent = file.parentFolder ? this.showFolder(`${file.parentFolder}/`) : '';
console.info(parent + fileName);
console.info(`${parent}${fileName || ''}`);
});
}

Expand Down Expand Up @@ -177,8 +179,10 @@ export class Cli {
if (!name) {
return '';
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return colors.bold[theme.folder](name);
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
return colors.bold[theme.folder](name) as string;
}

private createDumpFile(): Promise<string> {
Expand Down
15 changes: 8 additions & 7 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import * as fs from 'fs';
import { google } from 'googleapis';
import { GetTokenResponse } from 'google-auth-library/build/src/auth/oauth2client';
import { GetTokenResponse, OAuth2Client } from 'google-auth-library/build/src/auth/oauth2client';
import { Credentials } from 'google-auth-library/build/src/auth/credentials';
import readline from 'readline';
import colors from 'colors';
import Config from './config';
import { CredentialsFile, TokenFile } from './types';

export default class Auth {
public ready = true;
Expand All @@ -16,7 +17,7 @@ export default class Auth {
];
private readonly TOKEN_FILE = Config.TOKEN_FILE;
private readonly CREDENTIALS_FILE = Config.CREDENTIALS_FILE;
private _oAuth2Client: any = null;
private _oAuth2Client?: OAuth2Client;

constructor() {
if (!this.existsCredentials) {
Expand Down Expand Up @@ -45,11 +46,11 @@ export default class Auth {

public oAuth2Client(withToken = true) {
if (!this._oAuth2Client) {
const credentials = JSON.parse(fs.readFileSync(this.CREDENTIALS_FILE, 'utf8'));
const credentials = JSON.parse(fs.readFileSync(this.CREDENTIALS_FILE, 'utf8')) as CredentialsFile;
const { client_secret, client_id, redirect_uris } = credentials.installed;
this._oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]) as any;
this._oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
if (withToken) {
const token = JSON.parse(fs.readFileSync(this.TOKEN_FILE, 'utf8'));
const token = JSON.parse(fs.readFileSync(this.TOKEN_FILE, 'utf8')) as TokenFile;
this._oAuth2Client.setCredentials(token);
}
}
Expand Down Expand Up @@ -91,10 +92,10 @@ export default class Auth {
fs.writeFile(this.TOKEN_FILE, JSON.stringify(token), (err) => {
if (err) {
console.error(err);
reject(err);
void reject(err);
} else {
console.log(`${Config.TAG} Token stored to`, this.TOKEN_FILE);
resolve(true);
void resolve(true);
}
});
}
Expand Down
71 changes: 44 additions & 27 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from './types';
import os from 'os';
import Schema$File = drive_v3.Schema$File;
import { Socket } from 'net';

export class GDrive {
public readonly DEFAULT_FIELDS: FieldsType[] = ['createdTime', 'id', 'md5Checksum', 'mimeType', 'name', 'parents', 'trashed'];
Expand All @@ -37,7 +38,7 @@ export class GDrive {
});
}

private get auth(): any {
private get auth() {
return this.gdriveAuth.oAuth2Client(true);
}

Expand Down Expand Up @@ -75,39 +76,43 @@ export class GDrive {
return this.getListFiles(info);
}

async getFile(fileId?: string | null): Promise<Schema$File> {
async getFile(fileId?: string | null) {
await this.initiated;
if (!fileId) {
return Promise.reject(this.genericError(new Error('File id not found')));
}
const info: Params$Resource$Files$Get = { fileId };
return this.drive.files
.get(info)
.then(({ data }) => data)
.catch((e) => this.genericError(e));
const promise = this.drive.files.get(info).then(({ data }) => data);
promise.catch((e) => {
this.genericError(e);
});
return promise;
}

async emptyTrash() {
await this.initiated;
return this.drive.files.emptyTrash();
}

async deleteFile(file: Schema$File$Modded): Promise<void> {
async deleteFile(file: Schema$File$Modded) {
await this.initiated;
if (file.id) {
return this.drive.files
.delete({ fileId: file.id })
.then(({ data }) => {
const promise = this.drive.files.delete({ fileId: file.id }).then(({ data }) => {
if (file.name) {
console.warn(`${Config.TAG} Deleted ${file.isFolder ? 'folder' : 'file'}: ${file.name}`);
return data;
})
.catch((e) => this.genericError(e));
}
return data;
});
promise.catch((e) => {
this.genericError(e);
});
return promise;
}
}

async uploadFile(file: string, folderName?: string | boolean, options?: UploadOptionsBasic): Promise<Schema$File$Modded> {
async uploadFile(file: string, folderName?: string | boolean, options: UploadOptionsBasic = {}): Promise<Schema$File$Modded> {
await this.initiated;
const { create, replace } = options || ({} as any);
const { create = true, replace = false } = options;
const name = path.basename(file);
const mimeType = mime.contentType(name) || undefined;
const requestBody: Schema$File = {
Expand Down Expand Up @@ -137,19 +142,22 @@ export class GDrive {
};

const fileSize = fs.statSync(file).size;
const onUploadProgress = (evt: any) => {
const onUploadProgress = (evt: Socket) => {
const progress = (evt.bytesRead / fileSize) * 100;
if (progress === 100) {
console.warn(`${Config.TAG} Upload ${name}: ${Math.round(progress)}% complete`);
}
};
return this.drive.files
const promise = this.drive.files
.create(createOptions, { onUploadProgress })
.then(({ data }) => this.parseFileMeta(data))
.catch((e) => this.genericError(e))
.finally(() => {
readStream.destroy();
});
promise.catch((e) => {
this.genericError(e);
});
return promise;
}

async uploadFiles(
Expand Down Expand Up @@ -207,7 +215,7 @@ export class GDrive {
}

private getListFiles(info: Params$Resource$Files$List, files: Schema$File[] = []): Promise<Schema$File$Modded[]> {
return this.drive.files
const promise = this.drive.files
.list(info)
.then(async ({ data }) => {
files = files.concat(data.files as Schema$File[]);
Expand All @@ -218,8 +226,11 @@ export class GDrive {
return files;
}
})
.then((allFiles) => this.parseFilesMeta(allFiles))
.catch((e) => this.genericError(e));
.then((allFiles) => this.parseFilesMeta(allFiles));
promise.catch((e) => {
this.genericError(e);
});
return promise;
}

private async replaceExistingFolder(replace: boolean, name: string, folderId: string) {
Expand Down Expand Up @@ -285,7 +296,8 @@ export class GDrive {
return [...files].map((file) => this.parseFileMeta(file));
}

private genericError<T>(err: T): T {
private genericError<T = Error>(err: T): T {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.error(`${Config.TAG} The API returned an error: ${err}`);
return err;
}
Expand Down Expand Up @@ -317,18 +329,23 @@ export class GDrive {
return null;
}

private async createFolder(folderName: string): Promise<Schema$File> {
const createdFolder = await this.drive.files
private async createFolder(folderName: string) {
const promise = this.drive.files
.create({
requestBody: {
name: folderName,
mimeType: this.MIME_FOLDER
},
fields: 'id'
})
.then(({ data }) => data)
.catch((e) => this.genericError(e));
console.warn(`${Config.TAG} Created folder "${folderName}" with id: "${createdFolder.id}"`);
.then(({ data }) => data);
promise.catch((e) => {
this.genericError(e);
});
const createdFolder = await promise;
if (createdFolder?.id) {
console.warn(`${Config.TAG} Created folder "${folderName}" with id: "${createdFolder.id}"`);
}
return createdFolder;
}

Expand Down
22 changes: 22 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,25 @@ export interface UploadOptionsBasic {
export interface UploadOptions extends UploadOptionsBasic {
compress?: string | boolean;
}

export interface Installed {
client_id: string;
project_id: string;
auth_uri: string;
token_uri: string;
auth_provider_x509_cert_url: string;
client_secret: string;
redirect_uris: string[];
}

export interface CredentialsFile {
installed: Installed;
}

export interface TokenFile {
access_token: string;
refresh_token: string;
scope: string;
token_type: string;
expiry_date: number;
}

0 comments on commit 38657a7

Please sign in to comment.