UNPKG

@nativescript/core

Version:

A JavaScript library providing an easy to use api for interacting with iOS and Android platform APIs.

68 lines 2.2 kB
import { ImageSource } from '../../image-source'; import { File } from '../../file-system'; import { HttpResponseEncoding } from '../http-interfaces'; import { requestInternal } from '../http-request-internal'; import { getFilenameFromUrl, parseJSON } from './http-request-common'; const contentHandler = { toArrayBuffer() { return Uint8Array.from(this.raw.toByteArray()).buffer; }, toString(encoding) { let str; if (encoding) { str = decodeResponse(this.raw, encoding); } else { str = this.toNativeString(encoding); } if (typeof str === 'string') { return str; } else { throw new Error('Response content may not be converted to string'); } }, toJSON(encoding) { let str; if (encoding) { str = decodeResponse(this.raw, encoding); } else { str = this.toNativeString(encoding); } return parseJSON(str); }, toImage() { return this.toNativeImage().then((value) => new ImageSource(value)); }, toFile(destinationFilePath) { if (!destinationFilePath) { destinationFilePath = getFilenameFromUrl(this.requestURL); } let stream; try { // ensure destination path exists by creating any missing parent directories const file = File.fromPath(destinationFilePath); const javaFile = new java.io.File(destinationFilePath); stream = new java.io.FileOutputStream(javaFile); stream.write(this.raw.toByteArray()); return file; } catch (exception) { throw new Error(`Cannot save file with path: ${destinationFilePath}.`); } finally { if (stream) { stream.close(); } } }, }; export function request(options) { return requestInternal(options, contentHandler); } function decodeResponse(raw, encoding) { const charsetName = encoding === HttpResponseEncoding.GBK ? 'GBK' : 'UTF-8'; return raw.toString(charsetName); } //# sourceMappingURL=index.android.js.map