Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@robinbobin/react-native-google-drive-api-wrapper

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@robinbobin/react-native-google-drive-api-wrapper

This wrapper facilitates the use of the Google Drive API in React Native projects.

  • 1.2.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.1K
decreased by-18.49%
Maintainers
1
Weekly downloads
 
Created
Source

This wrapper facilitates the use of the google drive api.

It doesn't provide any authorization mechanism, so another package has to be used. I use @react-native-google-signin/google-signin (thanks for the great work, vonovak!).

  1. Installation
  2. Usage
  3. Version history

Installation

npm i --save @robinbobin/react-native-google-drive-api-wrapper

Usage

If something doesn't work as expected, please do have a look at an example project before opening an issue.

Quick example:

// = List files, create a binary file and read it = //

import { GoogleSignin } from "@react-native-google-signin/google-signin";
import {
  GDrive,
  MimeTypes
} from "@robinbobin/react-native-google-drive-api-wrapper";

// = Somewhere in your code = //
GoogleSignin.configure(...);
await GoogleSignin.signIn();

const gdrive = new GDrive();
gdrive.accessToken = (await GoogleSignin.getTokens()).accessToken;

console.log(await gdrive.files.list());

const id = (await gdrive.files.newMultipartUploader()
  .setData([1, 2, 3, 4, 5], MimeTypes.BINARY)
  .setRequestBody({
    name: "multipart_bin"
  })
  .execute()
).id;

console.log(await gdrive.files.getBinary(id));

  1. About
  2. Files
  3. GDrive
  4. GDriveApi
  5. HttpError
  6. ListQueryBuilder
  7. MimeTypes
  8. Permissions
  9. ResumableUploader
  10. UnexpectedFileCountError
  11. Uploader
About

Extending GDriveApi, this class gives access to various information.

NameDescription
get(queryParametersOrFields)Gets various information, returning an About resource if the call succeeds and fetchCoercesTypes is true. queryParametersOrFields can be an object containing the query parameters or a string, containing a fields value.
DataType

Uint8Array | number[] | string

Files

Extending GDriveApi, this class is used to manage files in a google drive. The parameter range for the methods that accept it is specified as here with one exception: <unit> is always bytes and mustn't be set. E.g.:

await gdrive.files.getBinary(fileId, null, "1-1");

will return the byte at index one.

NameTypeDescription
copy(fileId, queryParameters, requestBody = {})MethodCreates a copy of a file. Returns a Files resource if the call succeeds and fetchCoercesTypes is true.
createIfNotExists(queryParameters, uploader)MethodInvokes uploader.execute() and returns its result, if the file described with queryParameters doesn't exist. Returns the result of list(queryParameters) otherwise. Throws UnexpectedFileCountError if there are 2 or more files matching queryParameters.
delete(fileId)MethodDeletes a file. Returns an empty string if the call succeeds and fetchCoercesTypes is true.
emptyTrash()MethodPermanently deletes all of the user's trashed files. Returns an empty string if the call succeeds and fetchCoercesTypes is true.
export(fileId, queryParameters)MethodExports a Google Doc to the requested MIME type. Returns a Files resource if the call succeeds and fetchCoercesTypes is true.
generateIds(queryParameters)MethodGenerates file IDs. This info might seem interesting. Returns an Object if the call succeeds and fetchCoercesTypes is true.
get(fileId, queryParameters, range)MethodGets a file's metadata or content by ID. Returns the result of fetch() if the call succeeds, fetchCoercesTypes is ignored.
getBinary(fileId, queryParameters, range)MethodGets the content of a binary file. Returns Uint8Array if the call succeeds and fetchCoercesTypes is true.
getContent(fileId, queryParameters, range)MethodGets the content of any file. Returns the result of fetch() if the call succeeds, fetchCoercesTypes is ignored.
getJson(fileId, queryParameters)MethodGets the content of a json text file. Returns an Object if the call succeeds and fetchCoercesTypes is true.
getMetadata(fileId, queryParameters = {})MethodGets a file's metadata. Returns a Files resource if the call succeeds and fetchCoercesTypes is true.
getText(fileId, queryParameters, range)MethodGets the content of a text file. Returns a string if the call succeeds and fetchCoercesTypes is true.
list(queryParameters)MethodLists files. Returns an Object if the call succeeds and fetchCoercesTypes is true.

queryParameters.q can be a ListQueryBuilder instance.
multipartBoundaryString (read/write property)The boundary string to be used for multipart uploads. The default value is "foo_bar_baz".
newMediaUploader()MethodCreates an instance of MediaUploader, an Uploader descending class handling media uploads.
newMetadataOnlyUploader()MethodCreates an instance of MetadataOnlyUploader, an Uploader descending class handling metadata-only uploads.
newMultipartUploader()MethodCreates an instance of MultipartUploader, an Uploader descending class handling multipart uploads.
newResumableUploader()MethodCreates an instance of ResumableUploader.
GDrive

A GDrive instance stores your google sign-in token and the instances of the GDriveApi descendants.

NameTypeDescription
aboutAbout instance (read/write property)The instance to get various information.
accessTokenaccess token (read/write property)The access token to be used in subsequent calls to the api. Get the token from a package you choose to use.
filesFiles instance (read/write property)The instance to manage files in a google drive.
fetchCoercesTypes(read/write property)Manages fetchCoercesTypes of all the GDriveApi instances stored in this class instance.
fetchRejectsOnHttpErrors(read/write property)Manages fetchRejectsOnHttpErrors of all the GDriveApi instances stored in this class instance.
fetchTimeout(read/write property)Manages fetchTimeout of all the GDriveApi instances stored in this class instance.
permissionsPermissions instanceThe instance to manage file permissions.
GDriveApi

The base class for the classes that wrap individual parts of the google drive api.

NameTypeDescription
fetchCoercesTypesBoolean (read/write property)If true, the data returned from a successful api call is converted to the json, text or byte (Uint8Array) type. If false, no conversion is performed and the result of fetch() is returned as is. The type, the data is coerced to, is specified in the documentation of each method, that utilizes this property. The default value is true.
fetchRejectsOnHttpErrorsBoolean (read/write property)If true, unsuccessful api calls throw an instance of HttpError. If false, the result of fetch() is returned as is. The default value is true.
fetchTimeoutNumber (read/write property)Timeout in ms for fetch() invocations. The default value is 1500. If the value is negative, fetch() will wait infinitely.
HttpError

An instance of this class is thrown when an api call fails, if fetchRejectsOnHttpErrors is true for that api. All the properties are read-only.

NameTypeDescription
jsonObjectAn object containing the error. Can be undefined.
responseObjectThe result of fetch().
textStringThe error description obtained from the response.
IRequestUploadStatusResult

This interface is used as the return type of ResumableUploader.requestUploadStatus().

NameType
isCompleteBoolean
transferredByteCountNumber
IUploadChunkResult

Extending IRequestUploadStatusResult, describes the result of uploading a chunk of data. Its only field, json, is optional and will be missing when isComplete is false.

NameType
jsonany
ListQueryBuilder

A helper for building list() queries.

Example:

// = List files contained in the root folder and named "Untitled" = //
const folderIdNotItsName = "root";

await gdrive.files.list({
  q: new ListQueryBuilder()
    .e("name", "Untitled")
    .and()
    .in(folderIdNotItsName, "parents")
});
NameDescription
and()ands two subqueries.
contains(key, value, quoteValueIfString = true)key contains value
e(key, value, quoteValueIfString = true)key = value
g(key, value, quoteValueIfString = true)key > value
in(value, key, quoteValueIfString = true)value in key
l(key, value, quoteValueIfString = true)key < value
operator(left, operator, right, quoteLeftIfString, quoteRightIfString)A generic method to build all the other key/value relations.
or()ors two subqueries.
pop()Adds ).
push()Adds (.
toString()Stringifies the query (called internally by list()).
MimeTypes

Commonly used MIME types.

NameType
BINARYapplication/octet-stream
CSVtext/csv
FOLDERapplication/vnd.google-apps.folder
JSONapplication/json
JSON_UTF8application/json; charset=UTF-8
PDFapplication/pdf
TEXTtext/plain
Permissions

This class handles file permissions.

NameDescription
create(fileId, queryParameters, requestBody)Creates a permission, returning a Permissions resource if the call succeeds and fetchCoercesTypes is true.
delete(fileId, permissionId, queryParameters)Deletes a permission, returning an empty string if the call succeeds and fetchCoercesTypes is true.
ResumableUploader

An Uploader descendant, this class handles resumable uploads.

NameTypeDescription
requestUploadStatus()MethodReturns the current upload status, wrapped in a Promise.
setContentLength(contentLength: number)MethodOptional. Sets the content length. Can't be invoked after sending the initial upload request.
setDataType(dataType: string)MethodSets the data type when using multiple requests.
setShouldUseMultipleRequests(shouldUseMultipleRequests: boolean)MethodSpecifies whether multiple requests will be used to upload the data.
transferredByteCountRead property (Number)The current transferred byte count.
uploadChunk(chunk: DataType)MethodUploads a chunk of data, returning IUploadChunkResult, wrapped in a Promise.
UnexpectedFileCountError

An instance of this class is thrown when the real number of files differs from the expected. All the properties are read-only.

NameTypeDescription
expectedCountArray|NumberThe expected count.
realCountNumberReal count.
Uploader

Descendants of this class handle the create and update requests. All the methods except execute() can be chained.

NameDescription
execute()Executes the request, returning an Object if the call succeeds and fetchCoercesTypes is true.
setData(data, dataType)Sets the data and its MIME type.
setIdOfFileToUpdate(fileId)If this method is invoked, the request becomes an update request. Otherwise it's a creation request.
setIsBase64(isBase64)If it's a multipart request and the data supplied is Base64, this method can be invoked to add the header Content-Transfer-Encoding: base64 which is recognized by Google Drive.
setQueryParameters(queryParameters)Sets the query parameters.
setRequestBody(requestBody)Sets the request body.

Version history

Version numberChanges
v1.2.3Resumable uploads added.
v1.2.01. The package is rewritten in TypeScript.
2. The following properties are added to GDrive:
v1.1.0GDriveApi.fetchTimeout can be set to a negative value to make fetch() wait infinitely.
v1.0.1My example repo for this package is referenced in the readme.
v1.0.01. GDriveApi.fetchTimeout added.
2. HttpError and UnexpectedFileCountError: prototype names are specified and error messages are made more concise.
v0.6.01. UnexpectedFileCountError.
2. Files.createIfNotExists() is added.
v0.5.0ListQueryBuilder added.
v0.4.0Permissions added.
v0.3.0Initial documented release.


Written with StackEdit.

Keywords

FAQs

Package last updated on 26 Jun 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc