2.2.3 • Published 11 months ago

@robinbobin/react-native-google-drive-api-wrapper v2.2.3

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

This wrapper facilitates the use of the Google Drive API v3.

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!).

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

Table of contents

  1. Installation
  2. Usage
    1. Examples
    2. API
    3. Uploaders
    4. Other entities

Installation

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

Usage

Examples:

// General setup

import { GoogleSignin } from '@react-native-google-signin/google-signin'
import { INFINITE_TIMEOUT, GDrive } 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

// fetch() invocations wait infinitely
// gdrive.fetchTimeout = INFINITE_TIMEOUT
// List files

await gdrive.files.list(...)
// List files in `appDataFolder`

import { APP_DATA_FOLDER_ID } from '@robinbobin/react-native-google-drive-api-wrapper'

...

await gdrive.files.list({ ..., spaces: APP_DATA_FOLDER_ID })
// Create a binary file and read it

import { MIME_TYPES } from '@robinbobin/react-native-google-drive-api-wrapper'

...

const file = await gdrive.files.newMultipartUploader()
  .setData([1, 2, 3, 4, 5])
  .setDataMimeType(MIME_TYPES.application.octetStream)
  .setRequestBody({ name: "multipart_bin" })
  .execute()

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

API

  1. About
  2. Files
  3. GDrive
  4. Permissions

Notes:

  • STANDARD_PARAMETERS_FIELDS_ALL can be used instead of * as a value for fields in queryParameters of all methods:

    import { STANDARD_PARAMETERS_FIELDS_ALL } from '@robinbobin/react-native-google-drive-api-wrapper'
    
    ...
    
    await gdrive.about.get(STANDARD_PARAMETERS_FIELDS_ALL)
  • Query parameters of certain methods have string properties containing a comma-separated list of some values (e.g. spaces in list). This wrapper accepts string and string[] values for these properties. string values are passed as-is, and string[] values are converted to comma-separated lists.

About

This class gives information about the user, the user's Drive, and system capabilities.

NameDescription
get()Gets information about the user, the user's Drive, and system capabilities.Parameters:queryParameters: TAboutGetQueryParametersReturns:Promise<About resource>

Files

This class is used to manage files in a google drive.

Notes:

  • 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('bin_file_id', { range: '1-1' })

    will return the byte at index one.

  • ROOT_FOLDER_ID can be used instead of 'root':

    import { ROOT_FOLDER_ID } from '@robinbobin/react-native-google-drive-api-wrapper'
NameDescription
copy()Creates a copy of a file.Parameters:fileId: stringparameters?: IFilesCopyParametersReturns:Promise<File resource>
createIfNotExists()Conditionally creates a file resource.Parameters:queryParameters: query parametersuploader: an uploaderDescription:The function will use uploader to create a file resource if the file resource described with queryParameters doesn't exist.Returns:Promise<ICreateIfNotExistsResultType>Throws:UnexpectedFileCountError if there are 2 or more files matching queryParameters.
delete()Deletes a file without moving it to the trash.Parameters:fileId: stringReturns:Promise<void>
emptyTrash()Permanently deletes all of the user's trashed files.Returns:Promise<void>
export()Exports a Google Doc to the requested MIME type.Parameters:fileId: stringqueryParameters: query parametersReturns:Promise<TBlobToByteArrayResultType>
generateIds()Generates file IDs. This info might seem interesting.Parameters:queryParameters?: query parametersReturns:Promise<response body>
get()Gets the file metadata or content.Parameters:fileId: stringparameters?: IFilesGetParametersReturns:Promise<Response>
getBinary()Gets the file content as binary data.Parameters:fileId: stringparameters?: IFilesGetParametersReturns:Promise<TBlobToByteArrayResultType>
getContent()Gets the file content.Parameters:fileId: stringparameters?: IFilesGetParametersReturns:Promise<Response>
getJson<T = JsonObject>()Gets the file content as JSON.A template parameter can be supplied to type the return value. If omitted, a JSON object will be returned.Parameters:fileId: stringqueryParameters?: query parametersReturns:Promise<T>
getMetadata()Gets the file metadata.Parameters:fileId: stringqueryParameters?: query parametersReturns:Promise<File resource>
getText()Gets the file content as text.Parameters:fileId: stringparameters?: IFilesGetParametersReturns:Promise<string>
list()Lists files.Parameters:queryParameters?: query parametersqueryParameters.q can be a query string or a ListQueryBuilder instance.Returns:Promise<response body>
newMetadataOnlyUploader()Creates a class instance to perform a metadata-only upload.Returns:MetadataOnlyUploader
newMultipartUploader()Creates a class instance to perform a multipart upload.Returns:MultipartUploader
newResumableUploader()Creates a class instance to perform a resumable upload.Returns:ResumableUploader
newSimpleUploader()Creates a class instance to perform a simple upload.Returns:SimpleUploader

GDrive

A GDrive instance stores various api access parameters and the instances of the classes that wrap individual parts of the google drive api.

NameDescription
aboutThis read-only property stores the About instance.
accessTokenThis read/write property stores an access token to be used in subsequent calls to the apis.
fetchTimeoutThis read/write property stores a timeout in milliseconds for fetch() invocations. The default value is 1500. If the value is INFINITE_TIMEOUT, fetch() will wait infinitely.
filesThis read-only property stores the Files instance.
permissionsThis read-only property stores the Permissions instance.

Permissions

This class handles file permissions.

NameDescription
create()Creates a permission.Parameters:fileId: stringrequestBody: request bodyqueryParameters?: query parametersReturns:permission resource
delete()Deletes a permission.Parameters:fileId: stringpermissionId: stringqueryParameters?: query parametersReturns:Promise<void>

Uploaders

  1. MetadataOnlyUploader
  2. MultipartUploader
  3. ResumableUploader
  4. SimpleUploader
  5. Uploader
  6. UploaderWithDataMimeType
  7. UploaderWithSimpleData

MetadataOnlyUploader

An Uploader descendant, this class handles metadata-only uploads. It doesn't have own methods or properties. ExecuteResultType is set to file resource.

MultipartUploader

An UploaderWithSimpleData descendant, this class handles multipart uploads. ExecuteResultType is set to file resource.

NameDescription
setIsBase64()Conditionally adds header Content-Transfer-Encoding: base64 to the request.Parameters:isBase64: booleanDescription:This method should be invoked with isBase64 set to true if the data set with setData() is in Base64.Returns:this
setMultipartBoundary()Sets the boundary string to be used for this upload. The default is foo_bar_baz.Parameters:multipartBoundary: stringReturns:this

ResumableUploader

An UploaderWithDataMimeType descendant, this class handles resumable uploads. ExecuteResultType is set to ResumableUploadRequest.

NameDescription
setContentLength()Can be invoked to set the content length if it's known beforehand.Parameters:contentLength: numberReturns:this
setShouldUseMultipleRequests()Specifies whether multiple requests will be used to upload the data. The default behaviour is not to use multiple requests.Parameters:shouldUseMultipleRequests: booleanReturns:this

SimpleUploader

An UploaderWithSimpleData descendant, this class handles simple uploads. It doesn't have own methods or properties. ExecuteResultType is set to file resource.

Uploader

Descendants of this abstract class handle create and update requests.

Uploader has one template parameter, ExecuteResultType, set by descendants.

NameDescription
execute()Executes the request.Returns:Promise<ExecuteResultType>
setIdOfFileToUpdate()Sets the id of a file resource to be updated.Parameters:fileId: stringReturns:this
setQueryParameters()Sets query parameters.Parameters:queryParameters: query parameters (create or update)Returns:this
setRequestBody()Sets the request body.Parameters:requestBody: request body (create or update)Returns:this

UploaderWithDataMimeType

This abstract descendant of Uploader makes it possible to set the data mime type.

NameDescription
setDataMimeType()Sets the data mime type.Parameters:dataMimeType: stringMIME_TYPES can be used as an easy to use source of MIME constants:import { MIME_TYPES } from '@robinbobin/react-native-google-drive-api-wrapper'

UploaderWithSimpleData

This abstract descendant of UploaderWithDataMimeType makes it possible to set the data to be uploaded.

NameDescription
setData()Sets the data to be uploaded.Parameters:data: TSimpleDataReturns:this

Other entities

  1. FetchResponseError
  2. ICreateIfNotExistsResultType
  3. IFilesCopyParameters
  4. IFilesGetParameters
  5. IRequestUploadStatusResultType
  6. IUploadChunkResultType
  7. ListQueryBuilder
  8. ResumableUploadRequest
  9. TAboutGetQueryParameters
  10. TBlobToByteArrayResultType
  11. TSimpleData
  12. UnexpectedFileCountError

FetchResponseError

An instance of this class is thrown when a response to an api call is received, but its ok property is false.

NameDescription
jsonThis read-only property will contain a JSON object describing the error. It can be null.
responseThis read-only property will contain the result of fetch().

ICreateIfNotExistsResultType

This interface describes the result type of Files.createIfNotExists().

NameDescription
alreadyExistedWill be true if the file already existed before the method invocation, false otherwise.
resultWill contain a file resource, describing the existing file, if alreadyExisted is true. It will contain the result of invoking Uploader.execute() if alreadyExisted is false.

IFilesCopyParameters

This interface describes the parameters type for Files.copy().

NameDescription
queryParameters?query parameters
requestBody?file resource

IFilesGetParameters

This interface describes the parameters type for Files.get() and the like.

NameDescription
queryParameters?query parameters
range?Data range to get

IRequestUploadStatusResultType

This interface describes the result type of ResumableUploadRequest.requestUploadStatus().

NameDescription
isCompleteWill be true if the upload is completed, false otherwise.
transferredByteCountWill hold the number of bytes currently transferred.

IUploadChunkResultType

Extending IRequestUploadStatusResultType, this interface describes the result type of ResumableUploadRequest.uploadChunk().

NameDescription
json?Will contain a file resource, describing the file, if isComplete is true.

ListQueryBuilder

A helper class for building Files.list() queries. It uses the following type aliases:

type TKey = string
type TValue = JsonValue
type TValueQuotationFlag = boolean

type TKeyValueOperator = 'contains' | '=' | '>' | '<'
type TValueKeyOperator = 'in'

type TClause =
  | [TKey, TKeyValueOperator, TValue, TValueQuotationFlag?]
  | [TValue, TValueKeyOperator, TKey, TValueQuotationFlag?]
  • JsonValue matches any valid JSON value.
  • TValueQuotationFlag determines whether string values will be quoted. The default is true, meaning they will be quoted.
NameDescription
constructor()Parameters:...clause: TClause
and()Joins two subqueries with and.Parameters:...clause: TClause optionalReturns:this
or()Joins two subqueries with or.Parameters:...clause: TClause optionalReturns:this
pop()Adds ).Returns:this
push()Adds (.Parameters:...clause: TClause optionalReturns:this
toString()Stringifies the query.Returns:string

ResumableUploadRequest

This class serves as ExecuteResultType for ResumableUploader.

NameDescription
requestUploadStatus()Requests the current upload status.Returns:Promise<IRequestUploadStatusResultType>
setContentLength()Must be invoked when the content length is determined, if ResumableUploader.setContentLength() wasn't invoked.Parameters:contentLength: numberReturns:this
transferredByteCountThis read-only property will contain the current transferred byte count.
uploadChunk()Uploads a chunk of data.Parameters:chunk: TSimpleDataReturns:Promise<IUploadChunkResultType>

TAboutGetQueryParameters

This type alias describes the queryParameters type for About.get():

type TAboutGetQueryParameters = IStandardParameters | string | string[]

, where IStandardParameters are defined as here and string or string[] determines the value of fields.

TBlobToByteArrayResultType

This type alias describes the type of binary data returned from different api methods.

type TBlobToByteArrayResultType = Uint8Array | null

TSimpleData

This type alias describes the type of data for uploaders:

Uint8Array | string | number[]

UnexpectedFileCountError

An instance of this class is thrown by Files.createIfNotExists() if the number of matching files is not zero or one.

NameDescription
realCountWill contain the number of matching files.
2.2.1

11 months ago

2.2.0

11 months ago

2.2.3

11 months ago

2.2.2

11 months ago

2.1.0

11 months ago

1.2.4

2 years ago

1.2.3

3 years ago

1.2.2

3 years ago

1.1.0

4 years ago

1.0.1

4 years ago

1.2.1

4 years ago

1.0.0

4 years ago

0.6.0

4 years ago

0.5.0

4 years ago

0.4.0

4 years ago

0.3.0

4 years ago

0.2.0

4 years ago

0.0.1

4 years ago