@robinbobin/react-native-google-drive-api-wrapper
Advanced tools
Comparing version 1.2.2 to 1.2.3
@@ -1,4 +0,4 @@ | ||
import { blobToByteArray } from "./utils"; | ||
import GDriveApi from "../GDriveApi"; | ||
import HttpError from "../../HttpError"; | ||
import { blobToByteArray } from './utils' | ||
import GDriveApi from '../GDriveApi' | ||
import HttpError from '../../HttpError' | ||
@@ -11,99 +11,101 @@ /* | ||
fetch; | ||
fetch | ||
export type BodyType = Uint8Array | string; | ||
export type BodyType = Uint8Array | string | ||
export type FetchResponseType = 'blob' | 'json' | 'text' | ||
export type FetchResultType = Promise<any> | ||
export type FetchResponseType = "blob" | "json" | "text"; | ||
export default class Fetcher <SomeGDriveApi extends GDriveApi> { | ||
private readonly __abortController: AbortController; | ||
private readonly __gDriveApi: SomeGDriveApi; | ||
private readonly __init: RequestInit; | ||
private __resource?: RequestInfo; | ||
private __responseType?: FetchResponseType; | ||
private readonly abortController: AbortController | ||
private readonly fetchRejectsOnHttpErrors: boolean | ||
private readonly __gDriveApi: SomeGDriveApi | ||
private readonly init: RequestInit | ||
private resource?: RequestInfo | ||
private responseType?: FetchResponseType | ||
constructor(gDriveApi: SomeGDriveApi) { | ||
this.__abortController = new AbortController(); | ||
this.__gDriveApi = gDriveApi; | ||
constructor(gDriveApi: SomeGDriveApi, fetchRejectsOnHttpErrors?: boolean) { | ||
this.abortController = new AbortController() | ||
this.fetchRejectsOnHttpErrors = fetchRejectsOnHttpErrors ?? gDriveApi.fetchRejectsOnHttpErrors | ||
this.__gDriveApi = gDriveApi | ||
this.__init = { | ||
this.init = { | ||
headers: new Headers(), | ||
signal: this.__abortController.signal | ||
}; | ||
signal: this.abortController.signal | ||
} | ||
this.appendHeader("Authorization", `Bearer ${this.gDriveApi.accessToken}`); | ||
this.appendHeader('Authorization', `Bearer ${this.gDriveApi.accessToken}`) | ||
} | ||
appendHeader(name: string, value: any) { | ||
(this.__init.headers as Headers).append(name, value); | ||
appendHeader(name: string, value: string): Fetcher <SomeGDriveApi> { | ||
(this.init.headers as Headers).append(name, value) | ||
return this; | ||
return this | ||
} | ||
async fetch(resource?: RequestInfo, responseType?: FetchResponseType) { | ||
async fetch(resource?: RequestInfo, responseType?: FetchResponseType): FetchResultType { | ||
if (resource) { | ||
this.setResource(resource); | ||
this.setResource(resource) | ||
} | ||
if (responseType) { | ||
this.setResponseType(responseType); | ||
this.setResponseType(responseType) | ||
} | ||
if (this.gDriveApi.fetchTimeout >= 0) { | ||
setTimeout(() => this.__abortController.abort(), this.gDriveApi.fetchTimeout); | ||
setTimeout(() => this.abortController.abort(), this.gDriveApi.fetchTimeout) | ||
} | ||
let response = await fetch(this.__resource as RequestInfo, this.__init); | ||
let response: Response = await fetch(this.resource as RequestInfo, this.init) | ||
if (!response.ok) { | ||
if (this.gDriveApi.fetchRejectsOnHttpErrors) { | ||
throw await HttpError.create(response); | ||
if (this.fetchRejectsOnHttpErrors) { | ||
throw await HttpError.create(response) | ||
} | ||
return response; | ||
return response | ||
} | ||
if (!(this.gDriveApi.fetchCoercesTypes && this.__responseType)) { | ||
return response; | ||
if (!(this.gDriveApi.fetchCoercesTypes && this.responseType)) { | ||
return response | ||
} | ||
const result = await response[this.__responseType](); | ||
const result = await response[this.responseType]() | ||
return this.__responseType === "blob" ? blobToByteArray(result) : result; | ||
return this.responseType === 'blob' ? blobToByteArray(result) : result | ||
} | ||
get gDriveApi() { | ||
return this.__gDriveApi; | ||
return this.__gDriveApi | ||
} | ||
setBody(body: BodyType, contentType?: string) { | ||
this.__init.body = body; | ||
setBody(body: BodyType, contentType?: string): Fetcher <SomeGDriveApi> { | ||
this.init.body = body | ||
if (contentType) { | ||
this | ||
.appendHeader("Content-Length", body.length) | ||
.appendHeader("Content-Type", contentType); | ||
.appendHeader('Content-Length', body.length.toString()) | ||
.appendHeader('Content-Type', contentType) | ||
} | ||
return this; | ||
return this | ||
} | ||
setMethod(method: string) { | ||
this.__init.method = method; | ||
setMethod(method: string): Fetcher <SomeGDriveApi> { | ||
this.init.method = method | ||
return this; | ||
return this | ||
} | ||
setResource(resource: RequestInfo) { | ||
this.__resource = resource; | ||
setResource(resource: RequestInfo): Fetcher <SomeGDriveApi> { | ||
this.resource = resource | ||
return this; | ||
return this | ||
} | ||
setResponseType(responseType: FetchResponseType) { | ||
this.__responseType = responseType; | ||
setResponseType(responseType: FetchResponseType): Fetcher <SomeGDriveApi> { | ||
this.responseType = responseType | ||
return this; | ||
return this | ||
} | ||
}; | ||
} | ||
@@ -114,6 +116,6 @@ async function exportedFetch <SomeGDriveApi extends GDriveApi> ( | ||
responseType: FetchResponseType | ||
) { | ||
return new Fetcher(gDriveApi).fetch(resource, responseType); | ||
): FetchResultType { | ||
return new Fetcher(gDriveApi).fetch(resource, responseType) | ||
} | ||
export { exportedFetch as fetch }; | ||
export { exportedFetch as fetch } |
@@ -76,3 +76,3 @@ import { ArrayStringifier } from "simple-common-utils"; | ||
queryParameters = {} | ||
}: UriParameters) { | ||
}: UriParameters): string { | ||
const uri = ["https://www.googleapis.com"]; | ||
@@ -79,0 +79,0 @@ |
@@ -7,3 +7,3 @@ import { toByteArray } from "base64-js"; | ||
export function blobToByteArray(blob: Blob) { | ||
export function blobToByteArray(blob: Blob): Promise <Uint8Array | null> { | ||
return new Promise((resolve, reject) => { | ||
@@ -14,9 +14,18 @@ const reader = new FileReader(); | ||
reader.onload = () => ( | ||
resolve( | ||
!reader.result ? null | ||
: typeof reader.result === "string" ? toByteArray(reader.result.split("data:application/octet-stream;base64,")[1]) | ||
: reader.result | ||
) | ||
); | ||
reader.onload = () => { | ||
if (!reader.result) { | ||
resolve(null); | ||
return; | ||
} | ||
if (typeof reader.result === "string") { | ||
const b64 = reader.result.split("data:application/octet-stream;base64,")[1]; | ||
resolve(toByteArray(b64)); | ||
return | ||
} | ||
resolve(new Uint8Array(reader.result)) | ||
}; | ||
@@ -23,0 +32,0 @@ reader.readAsDataURL(blob); |
@@ -6,3 +6,7 @@ import FilesApi from "./FilesApi"; | ||
} from "../aux/Fetcher"; | ||
import Uploader from "../aux/Uploader"; | ||
import MediaUploader from "../aux/uploaders/MediaUploader"; | ||
import MetadataOnlyUploader from "../aux/uploaders/MetadataOnlyUploader"; | ||
import MultipartUploader from "../aux/uploaders/MultipartUploader"; | ||
import ResumableUploader from "../aux/uploaders/ResumableUploader"; | ||
import Uploader from "../aux/uploaders/Uploader"; | ||
import Uris from "../aux/Uris"; | ||
@@ -21,5 +25,7 @@ import MimeTypes from "../../MimeTypes"; | ||
async createIfNotExists(queryParameters: object, uploader: Uploader): Promise <CreateIfNotExistsResult> { | ||
uploader.setIdOfFileToUpdate(); | ||
const files = (await this.list(queryParameters)).files; | ||
if (!this.fetchRejectsOnHttpErrors && !files.ok) { | ||
return files | ||
} | ||
@@ -110,16 +116,16 @@ switch (files.length) { | ||
newMediaUploader() { | ||
return new Uploader(new Fetcher(this), "media"); | ||
return new MediaUploader(new Fetcher(this)); | ||
} | ||
newMetadataOnlyUploader() { | ||
return new Uploader(new Fetcher(this)); | ||
return new MetadataOnlyUploader(new Fetcher(this)); | ||
} | ||
newMultipartUploader() { | ||
return new Uploader(new Fetcher(this), "multipart"); | ||
return new MultipartUploader(new Fetcher(this)); | ||
} | ||
// newResumableUploader() { | ||
// return new Uploader(new Fetcher(this), "resumable"); | ||
// } | ||
newResumableUploader() { | ||
return new ResumableUploader(new Fetcher(this)); | ||
} | ||
@@ -126,0 +132,0 @@ __get( |
@@ -1,11 +0,11 @@ | ||
export default class MimeTypes { | ||
static BINARY = "application/octet-stream"; | ||
static CSV = "text/csv"; | ||
static FOLDER = "application/vnd.google-apps.folder"; | ||
static JSON = "application/json"; | ||
static JSON_UTF8 = "; charset=UTF-8"; | ||
static PDF = "application/pdf"; | ||
static TEXT = "text/plain"; | ||
}; | ||
enum MimeTypes { | ||
BINARY = 'application/octet-stream', | ||
CSV = 'text/csv', | ||
FOLDER = 'application/vnd.google-apps.folder', | ||
JSON = 'application/json', | ||
JSON_UTF8 = 'application/json; charset=UTF-8', | ||
PDF = 'application/pdf', | ||
TEXT = 'text/plain' | ||
} | ||
MimeTypes.JSON_UTF8 = `${MimeTypes.JSON}${MimeTypes.JSON_UTF8}`; | ||
export default MimeTypes |
@@ -27,3 +27,3 @@ { | ||
}, | ||
"version": "1.2.2" | ||
"version": "1.2.3" | ||
} |
@@ -56,4 +56,5 @@ This wrapper facilitates the use of the [google drive api](https://developers.google.com/drive/v3/reference/). | ||
8. <a name="c_permissions"></a>[Permissions](#permissions) | ||
9. <a name="c_unexpected_file_count_error"></a>[UnexpectedFileCountError](#unexpected_file_count_error) | ||
10. <a name="c_uploader"></a>[Uploader](#uploader) | ||
9. <a name="c_resumable_uploader"></a>[ResumableUploader](#resumable_uploader) | ||
10. <a name="c_unexpected_file_count_error"></a>[UnexpectedFileCountError](#unexpected_file_count_error) | ||
11. <a name="c_uploader"></a>[Uploader](#uploader) | ||
@@ -68,2 +69,6 @@ #### <a name="about"></a>[About](#c_about) | ||
#### <a name="data_type"></a>DataType | ||
Uint8Array | number[] | string | ||
#### <a name="filesfiles"></a>[Files](#c_files) | ||
@@ -85,3 +90,3 @@ | ||
export(fileId, queryParameters)|Method|[Exports](https://developers.google.com/drive/api/v3/reference/files/export) a Google Doc to the requested MIME type. Returns a [Files resource](https://developers.google.com/drive/api/v3/reference/files#resource) if the call succeeds and [fetchCoercesTypes](#gdriveapi_fetch_coerces_types) is `true`. | ||
generateIds(queryParameters)|Method|[Generates](https://developers.google.com/drive/api/v3/reference/files/generateIds) file IDs. Returns an `Object` if the call succeeds and [fetchCoercesTypes](#gdriveapi_fetch_coerces_types) is `true`. | ||
generateIds(queryParameters)|Method|[Generates](https://developers.google.com/drive/api/v3/reference/files/generateIds) file IDs. [This info](https://developers.google.com/drive/api/guides/manage-uploads#use_a_pre-generated_id_to_upload_files) might seem interesting. Returns an `Object` if the call succeeds and [fetchCoercesTypes](#gdriveapi_fetch_coerces_types) is `true`. | ||
get(fileId, queryParameters, range)|Method|[Gets](https://developers.google.com/drive/api/v3/reference/files/get) a file's metadata or content by ID. Returns the result of [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) if the call succeeds, [fetchCoercesTypes](#gdriveapi_fetch_coerces_types) is ignored. | ||
@@ -95,9 +100,10 @@ getBinary(fileId, queryParameters, range)|Method|Gets the content of a binary file. Returns `Uint8Array` if the call succeeds and [fetchCoercesTypes](#gdriveapi_fetch_coerces_types) is `true`. | ||
multipartBoundary|String (read/write property)|The boundary string to be used for multipart uploads. The default value is `"foo_bar_baz"`. | ||
newMediaUploader()|Method|Creates an [Uploader](#uploader) instance with `uploadType` of `media`. | ||
newMetadataOnlyUploader()|Method|Creates a metadata-only [Uploader](#uploader) instance. | ||
newMultipartUploader()|Method|Creates an [Uploader](#uploader) instance with `uploadType` of `multipart`. | ||
newMediaUploader()|Method|Creates an instance of `MediaUploader`, an [Uploader](#uploader) descending class handling `media` uploads. | ||
newMetadataOnlyUploader()|Method|Creates an instance of `MetadataOnlyUploader`, an [Uploader](#uploader) descending class handling metadata-only uploads. | ||
newMultipartUploader()|Method|Creates an instance of `MultipartUploader`, an [Uploader](#uploader) descending class handling `multipart` uploads. | ||
<a name="filesfiles_newResumableUploader"></a>newResumableUploader()|Method|Creates an instance of [ResumableUploader](#resumable_uploader). | ||
#### <a name="gdrive"></a>[GDrive](#c_gdrive) | ||
A `GDrive` instance stores your google sign-in token and the class instances you create to utilize the google drive api. | ||
A `GDrive` instance stores your google sign-in token and the instances of the [GDriveApi](gdriveapi) descendants. | ||
@@ -134,2 +140,19 @@ Name|Type|Description | ||
#### <a name="i_request_upload_status_result"></a>IRequestUploadStatusResult | ||
This interface is used as the return type of [ResumableUploader.requestUploadStatus()](#resumable_uploader_request_upload_status). | ||
Name|Type | ||
-|- | ||
isComplete|Boolean | ||
transferredByteCount|Number | ||
#### <a name="i_upload_chunk_result"></a>IUploadChunkResult | ||
Extending [IRequestUploadStatusResult](#i_request_upload_status_result), describes the result of [uploading a chunk of data](#resumable_uploader_upload_chunk). Its only field, `json`, is optional and will be missing when `isComplete` is `false`. | ||
Name|Type | ||
-|- | ||
json|any | ||
#### <a name="list_query_builder"></a>[ListQueryBuilder](#c_list_query_builder) | ||
@@ -167,3 +190,3 @@ | ||
Commonly used MIME types. The class contains only static fields. | ||
Commonly used MIME types. | ||
@@ -189,2 +212,15 @@ Name|Type | ||
#### <a name="resumable_uploader"></a>[ResumableUploader](#c_resumable_uploader) | ||
An [Uploader](#uploader) descendant, this class handles resumable uploads. | ||
Name|Type|Description | ||
-|-|- | ||
<a name="resumable_uploader_request_upload_status"></a>requestUploadStatus()|Method|Returns the current [upload status](#i_request_upload_status_result), wrapped in a `Promise`. | ||
setContentLength(contentLength: number)|Method|Optional. Sets the content length. **Can't be invoked after sending the initial upload request.** | ||
setDataType(dataType: string)|Method|Sets the data type when using [multiple requests](#resumable_uploader_should_use_multiple_requests). | ||
<a name="resumable_uploader_should_use_multiple_requests"></a>setShouldUseMultipleRequests(shouldUseMultipleRequests: boolean)|Method|Specifies whether multiple requests will be used to upload the data. | ||
transferredByteCount|Read property (Number)|The current transferred byte count. | ||
<a name="resumable_uploader_upload_chunk"></a>uploadChunk(chunk: [DataType](#data_type))|Method|Uploads a chunk of data, returning [IUploadChunkResult](#i_upload_chunk_result), wrapped in a `Promise`. | ||
#### <a name="unexpected_file_count_error"></a>[UnexpectedFileCountError](#c_unexpected_file_count_error) | ||
@@ -199,6 +235,5 @@ | ||
#### <a name="uploader"></a>[Uploader](#c_uploader) | ||
This class handles the [create](https://developers.google.com/drive/api/v3/reference/files/create) and [update](https://developers.google.com/drive/api/v3/reference/files/update) requests. Currently only `media`, `multipart` and `metadata-only` requests are supported. All the methods except `execute()` can be chained. | ||
Descendants of this class handle the [create](https://developers.google.com/drive/api/v3/reference/files/create) and [update](https://developers.google.com/drive/api/v3/reference/files/update) requests. All the methods except `execute()` can be chained. | ||
@@ -218,2 +253,3 @@ Name|Description | ||
-|- | ||
v1.2.3|[Resumable uploads](#filesfiles_newResumableUploader) added. | ||
v1.2.0|1. The package is rewritten in TypeScript.<br>2. The following properties are added to [`GDrive`](#gdrive):<br><ul><li>[`fetchCoercesTypes`](#gdrive_fetch_coerces_types)</li><li>[`fetchRejectsOnHttpErrors`](#gdrive_fetch_rejects_on_http_errors)</li><li>[`fetchTimeout`](#gdrive_fetch_timeout)</li></ul> | ||
@@ -220,0 +256,0 @@ v1.1.0|[`GDriveApi.fetchTimeout`](#gdriveapi_fetch_timeout) can be set to a negative value to make `fetch()` wait infinitely. |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
46005
21
855
259