This wrapper facilitates the use of the Google Drive API in React Native projects.
npm install @robinbobin/react-native-google-drive-api-wrapperThis 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 these example projects before opening an issue: for React Native, for Expo.
1. Installation
2. Usage
1. Examples
1. API
1. Uploaders
1. Other entities
npm i @robinbobin/react-native-google-drive-api-wrapper
// 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))
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.
This class gives information about the user, the user's Drive, and system capabilities.
| Name | Description |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| get() | Gets information about the user, the user's Drive, and system capabilities.
Parameters:
queryParameters: TAboutGetQueryParametersPromise<IAbout>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:
\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'
| Name | Description |
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| copy() | Creates a copy of a file.
Parameters:
fileId: stringparameters?: IFilesCopyParametersPromise<IFileOutput>createIfNotExists() | Conditionally creates a file resource.queryParameters: IFilesListQueryParametersuploader: an uploaderuploader to create a file resource if the file resource described with queryParameters doesn't exist.Promise<ICreateIfNotExistsResultType>UnexpectedFileCountError if there are 2 or more files matching queryParameters.delete() | Deletes a file without moving it to the trash.fileId: stringPromiseemptyTrash() | Permanently deletes all of the user's trashed files.Promiseexport() | Exports a Google Doc to the requested MIME type.fileId: stringqueryParameters: IFilesExportQueryParametersPromise<TBlobToByteArrayResultType>generateIds() | Generates file IDs. This info might seem interesting.queryParameters?: IFilesGenerateIdsQueryParametersPromise<IFilesGenerateIdsResultType>get() | Gets the file metadata or content.fileId: stringparameters?: IFilesGetParametersPromise<Response>getBinary() | Gets the file content as binary data.fileId: stringparameters?: IFilesGetParametersPromise<TBlobToByteArrayResultType>getContent() | Gets the file content.fileId: stringparameters?: IFilesGetParametersPromise<Response>getJson() | Gets the file content as JSON.fileId: stringqueryParameters?: IFilesGetQueryParametersPromisegetMetadata() | Gets the file metadata.fileId: stringqueryParameters?: IFilesGetQueryParametersPromise<IFileOutput>getText() | Gets the file content as text.fileId: stringparameters?: IFilesGetParametersPromiselist() | Lists files.queryParameters?: IFilesListQueryParametersqueryParameters.q can be a query string or a ListQueryBuilder instance.Promise<IFilesListResultType>newMetadataOnlyUploader() | Creates a class instance to perform a metadata-only upload.newMultipartUploader() | Creates a class instance to perform a multipart upload.MultipartUploader |newResumableUploader() | Creates a class instance to perform a resumable upload.ResumableUploader |newSimpleUploader() | Creates a class instance to perform a simple upload.SimpleUploader |A GDrive instance stores various api access parameters and the instances of the classes that wrap individual parts of the google drive api.
| Name | Description |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| about | This read-only property stores the About instance. |
| accessToken | This read/write property stores an access token to be used in subsequent calls to the apis. |
| fetchTimeout | This 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. |
| files | This read-only property stores the Files instance. |
| permissions | This read-only property stores the Permissions instance. |
This class handles file permissions.
| Name | Description |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| create() | Creates a permission.
Parameters:
fileId: stringrequestBody: IPermissionInputqueryParameters?: IPermissionsCreateQueryParametersdelete() | Deletes a permission.fileId: stringpermissionId: stringqueryParameters?: IPermissionsDeleteQueryParametersPromise1. MetadataOnlyUploader
1. MultipartUploader
1. ResumableUploader
1. SimpleUploader
1. Uploader
1. UploaderWithDataMimeType
1. UploaderWithSimpleData
An Uploader descendant, this class handles metadata-only uploads. It doesn't have own methods or properties. ExecuteResultType is set to IFileOutput.
An UploaderWithSimpleData descendant, this class handles multipart uploads. ExecuteResultType is set to IFileOutput.
| Name | Description |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| setIsBase64() | Conditionally adds header Content-Transfer-Encoding: base64 to the request.
Parameters:
isBase64: booleanisBase64 set to true if the data set with setData() is in Base64.thissetMultipartBoundary() | Sets the boundary string to be used for this upload. The default is foo_bar_baz.multipartBoundary: stringthisAn UploaderWithDataMimeType descendant, this class handles resumable uploads. ExecuteResultType is set to ResumableUploadRequest.
| Name | Description |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| setContentLength() | Can be invoked to set the content length if it's known beforehand.
Parameters:
contentLength: numberthissetShouldUseMultipleRequests() | Specifies whether multiple requests will be used to upload the data. The default behaviour is not to use multiple requests.shouldUseMultipleRequests: booleanthisAn UploaderWithSimpleData descendant, this class handles simple uploads. It doesn't have own methods or properties. ExecuteResultType is set to IFileOutput.
Descendants of this abstract class handle create and update requests.
Uploader has one template parameter, ExecuteResultType, set by descendants.
| Name | Description |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| execute() | Executes the request.
Returns:
Promise<ExecuteResultType>setIdOfFileToUpdate() | Sets the id of a file resource to be updated.fileId: stringthissetQueryParameters() | Sets query parameters.thissetRequestBody() | Sets the request body.thisThis abstract descendant of Uploader makes it possible to set the data mime type.
| Name | Description |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 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' |This abstract descendant of UploaderWithDataMimeType makes it possible to set the data to be uploaded.
| Name | Description |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| setData() | Sets the data to be uploaded.
Parameters:
data: TSimpleDatathis1. FetchResponseError
1. ICreateIfNotExistsResultType
1. IFilesCopyParameters
1. IFilesGetParameters
1. IRequestUploadStatusResultType
1. IUploadChunkResultType
1. ListQueryBuilder
1. ResumableUploadRequest
1. TAboutGetQueryParameters
1. TBlobToByteArrayResultType
1. TSimpleData
1. UnexpectedFileCountError
An instance of this class is thrown when a response to an api call is received, but its ok property is false.
| Name | Description |
| ---------- | ----------------------------------------------------------------------------------------------------------------------- |
| json | This read-only property will contain a JSON object describing the error. It can be null. |
| response | This read-only property will contain the result of fetch(). |
This interface describes the result type of Files.createIfNotExists().
| Name | Description |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| alreadyExisted | Will be true if the file already existed before the method invocation, false otherwise. |
| result | Will be IFileOutput, describing the existing file, if alreadyExisted is true. It will contain the result of invoking Uploader.execute() if alreadyExisted is false. |
This interface describes the parameters type for Files.copy().
| Name | Description |
| ------------------ | ------------------------------------------------------------------------------------------------------------------ |
| queryParameters? | IFilesCopyQueryParameters |
| requestBody? | IFileInput |
This interface describes the parameters type for Files.get() and the like.
| Name | Description |
| ------------------ | ---------------------------------------------------------------------------------------------------------------- |
| queryParameters? | IFilesGetQueryParameters |
| range? | Data range to get |
This interface describes the result type of ResumableUploadRequest.requestUploadStatus().
| Name | Description |
| ------------------------------------------------------------------------ | ------------------------------------------------------------- |
| isComplete | Will be true if the upload is completed, false otherwise. |
| transferredByteCount | Will hold the number of bytes currently transferred. |
Extending IRequestUploadStatusResultType, this interface describes the result type of ResumableUploadRequest.uploadChunk().
| Name | Description |
| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| json? | IFileOutput, describing the file, if isComplete is true. |
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.
| Name | Description |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| constructor() | Parameters:
...clause: TClauseand() | Joins two subqueries with and....clause: TClause _optional_thisor() | Joins two subqueries with or....clause: TClause _optional_thispop() | Adds ).thispush() | Adds (....clause: TClause _optional_thistoString() | Stringifies the query.stringThis class serves as ExecuteResultType for ResumableUploader.
| Name | Description |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 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.contentLength: numberthistransferredByteCount | This read-only property will contain the current transferred byte count. |uploadChunk() | Uploads a chunk of data.chunk: TSimpleDataPromise<IUploadChunkResultType>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.
This type alias describes the type of binary data returned from different api methods.
type TBlobToByteArrayResultType = Uint8Array | null
This type alias describes the type of data for uploaders:
Uint8Array | string | number[]
An instance of this class is thrown by Files.createIfNotExists() if the number of matching files is not zero or one.
| Name | Description |
| ----------- | ------------------------------------------ |
| realCount | Will contain the number of matching files. |