@minotaur-ergo/http
Advanced tools
Comparing version 0.0.7 to 0.0.8
@@ -10,3 +10,3 @@ { | ||
"name": "request", | ||
"signature": "(options: HttpOptions) => Promise<HttpResponse>", | ||
"signature": "(options: { value: string; }) => Promise<{ value: string; }>", | ||
"parameters": [ | ||
@@ -16,108 +16,10 @@ { | ||
"docs": "", | ||
"type": "HttpOptions" | ||
"type": "{ value: string; }" | ||
} | ||
], | ||
"returns": "Promise<HttpResponse>", | ||
"returns": "Promise<{ value: string; }>", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpResponse", | ||
"HttpOptions" | ||
], | ||
"complexTypes": [], | ||
"slug": "request" | ||
}, | ||
{ | ||
"name": "get", | ||
"signature": "(options: HttpOptions) => Promise<HttpResponse>", | ||
"parameters": [ | ||
{ | ||
"name": "options", | ||
"docs": "", | ||
"type": "HttpOptions" | ||
} | ||
], | ||
"returns": "Promise<HttpResponse>", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpResponse", | ||
"HttpOptions" | ||
], | ||
"slug": "get" | ||
}, | ||
{ | ||
"name": "post", | ||
"signature": "(options: HttpOptions) => Promise<HttpResponse>", | ||
"parameters": [ | ||
{ | ||
"name": "options", | ||
"docs": "", | ||
"type": "HttpOptions" | ||
} | ||
], | ||
"returns": "Promise<HttpResponse>", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpResponse", | ||
"HttpOptions" | ||
], | ||
"slug": "post" | ||
}, | ||
{ | ||
"name": "put", | ||
"signature": "(options: HttpOptions) => Promise<HttpResponse>", | ||
"parameters": [ | ||
{ | ||
"name": "options", | ||
"docs": "", | ||
"type": "HttpOptions" | ||
} | ||
], | ||
"returns": "Promise<HttpResponse>", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpResponse", | ||
"HttpOptions" | ||
], | ||
"slug": "put" | ||
}, | ||
{ | ||
"name": "patch", | ||
"signature": "(options: HttpOptions) => Promise<HttpResponse>", | ||
"parameters": [ | ||
{ | ||
"name": "options", | ||
"docs": "", | ||
"type": "HttpOptions" | ||
} | ||
], | ||
"returns": "Promise<HttpResponse>", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpResponse", | ||
"HttpOptions" | ||
], | ||
"slug": "patch" | ||
}, | ||
{ | ||
"name": "delete", | ||
"signature": "(options: HttpOptions) => Promise<HttpResponse>", | ||
"parameters": [ | ||
{ | ||
"name": "options", | ||
"docs": "", | ||
"type": "HttpOptions" | ||
} | ||
], | ||
"returns": "Promise<HttpResponse>", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpResponse", | ||
"HttpOptions" | ||
], | ||
"slug": "delete" | ||
} | ||
@@ -127,191 +29,6 @@ ], | ||
}, | ||
"interfaces": [ | ||
{ | ||
"name": "HttpResponse", | ||
"slug": "httpresponse", | ||
"docs": "", | ||
"tags": [], | ||
"methods": [], | ||
"properties": [ | ||
{ | ||
"name": "data", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [], | ||
"type": "any" | ||
}, | ||
{ | ||
"name": "status", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [], | ||
"type": "number" | ||
}, | ||
{ | ||
"name": "headers", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpHeaders" | ||
], | ||
"type": "HttpHeaders" | ||
}, | ||
{ | ||
"name": "url", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [], | ||
"type": "string" | ||
} | ||
] | ||
}, | ||
{ | ||
"name": "HttpHeaders", | ||
"slug": "httpheaders", | ||
"docs": "", | ||
"tags": [], | ||
"methods": [], | ||
"properties": [] | ||
}, | ||
{ | ||
"name": "HttpOptions", | ||
"slug": "httpoptions", | ||
"docs": "", | ||
"tags": [], | ||
"methods": [], | ||
"properties": [ | ||
{ | ||
"name": "url", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [], | ||
"type": "string" | ||
}, | ||
{ | ||
"name": "method", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [], | ||
"type": "string | undefined" | ||
}, | ||
{ | ||
"name": "params", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpParams" | ||
], | ||
"type": "HttpParams" | ||
}, | ||
{ | ||
"name": "data", | ||
"tags": [], | ||
"docs": "Note: On Android and iOS, data can only be a string or a JSON.\nFormData, Blob, ArrayBuffer, and other complex types are only directly supported on web\nor through enabling `CapacitorHttp` in the config and using the patched `window.fetch` or `XMLHttpRequest`.\n\nIf you need to send a complex type, you should serialize the data to base64\nand set the `headers[\"Content-Type\"]` and `dataType` attributes accordingly.", | ||
"complexTypes": [], | ||
"type": "any" | ||
}, | ||
{ | ||
"name": "headers", | ||
"tags": [], | ||
"docs": "", | ||
"complexTypes": [ | ||
"HttpHeaders" | ||
], | ||
"type": "HttpHeaders" | ||
}, | ||
{ | ||
"name": "readTimeout", | ||
"tags": [], | ||
"docs": "How long to wait to read additional data. Resets each time new\ndata is received", | ||
"complexTypes": [], | ||
"type": "number | undefined" | ||
}, | ||
{ | ||
"name": "connectTimeout", | ||
"tags": [], | ||
"docs": "How long to wait for the initial connection.", | ||
"complexTypes": [], | ||
"type": "number | undefined" | ||
}, | ||
{ | ||
"name": "disableRedirects", | ||
"tags": [], | ||
"docs": "Sets whether automatic HTTP redirects should be disabled", | ||
"complexTypes": [], | ||
"type": "boolean | undefined" | ||
}, | ||
{ | ||
"name": "webFetchExtra", | ||
"tags": [], | ||
"docs": "Extra arguments for fetch when running on the web", | ||
"complexTypes": [ | ||
"RequestInit" | ||
], | ||
"type": "RequestInit" | ||
}, | ||
{ | ||
"name": "responseType", | ||
"tags": [], | ||
"docs": "This is used to parse the response appropriately before returning it to\nthe requestee. If the response content-type is \"json\", this value is ignored.", | ||
"complexTypes": [ | ||
"HttpResponseType" | ||
], | ||
"type": "HttpResponseType" | ||
}, | ||
{ | ||
"name": "shouldEncodeUrlParams", | ||
"tags": [], | ||
"docs": "Use this option if you need to keep the URL unencoded in certain cases\n(already encoded, azure/firebase testing, etc.). The default is _true_.", | ||
"complexTypes": [], | ||
"type": "boolean | undefined" | ||
}, | ||
{ | ||
"name": "dataType", | ||
"tags": [], | ||
"docs": "This is used if we've had to convert the data from a JS type that needs\nspecial handling in the native layer", | ||
"complexTypes": [], | ||
"type": "'file' | 'formData' | undefined" | ||
} | ||
] | ||
}, | ||
{ | ||
"name": "HttpParams", | ||
"slug": "httpparams", | ||
"docs": "", | ||
"tags": [], | ||
"methods": [], | ||
"properties": [] | ||
} | ||
], | ||
"interfaces": [], | ||
"enums": [], | ||
"typeAliases": [ | ||
{ | ||
"name": "HttpResponseType", | ||
"slug": "httpresponsetype", | ||
"docs": "", | ||
"types": [ | ||
{ | ||
"text": "'arraybuffer'", | ||
"complexTypes": [] | ||
}, | ||
{ | ||
"text": "'blob'", | ||
"complexTypes": [] | ||
}, | ||
{ | ||
"text": "'json'", | ||
"complexTypes": [] | ||
}, | ||
{ | ||
"text": "'text'", | ||
"complexTypes": [] | ||
}, | ||
{ | ||
"text": "'document'", | ||
"complexTypes": [] | ||
} | ||
] | ||
} | ||
], | ||
"typeAliases": [], | ||
"pluginConfigs": [] | ||
} |
@@ -1,56 +0,7 @@ | ||
declare type HttpResponseType = 'arraybuffer' | 'blob' | 'json' | 'text' | 'document'; | ||
export interface HttpPlugin { | ||
request(options: HttpOptions): Promise<HttpResponse>; | ||
get(options: HttpOptions): Promise<HttpResponse>; | ||
post(options: HttpOptions): Promise<HttpResponse>; | ||
put(options: HttpOptions): Promise<HttpResponse>; | ||
patch(options: HttpOptions): Promise<HttpResponse>; | ||
delete(options: HttpOptions): Promise<HttpResponse>; | ||
request(options: { | ||
value: string; | ||
}): Promise<{ | ||
value: string; | ||
}>; | ||
} | ||
export interface HttpOptions { | ||
url: string; | ||
method?: string; | ||
params?: HttpParams; | ||
data?: any; | ||
headers?: HttpHeaders; | ||
/** | ||
* How long to wait to read additional data. Resets each time new | ||
* data is received | ||
*/ | ||
readTimeout?: number; | ||
/** | ||
* How long to wait for the initial connection. | ||
*/ | ||
connectTimeout?: number; | ||
/** | ||
* Sets whether automatic HTTP redirects should be disabled | ||
*/ | ||
disableRedirects?: boolean; | ||
/** | ||
* Extra arguments for fetch when running on the web | ||
*/ | ||
webFetchExtra?: RequestInit; | ||
/** | ||
* This is used to parse the response appropriately before returning it to | ||
* the requestee. If the response content-type is "json", this value is ignored. | ||
*/ | ||
responseType?: HttpResponseType; | ||
/** | ||
* Use this option if you need to keep the URL unencoded in certain cases | ||
* (already encoded, azure/firebase testing, etc.). The default is _true_. | ||
*/ | ||
shouldEncodeUrlParams?: boolean; | ||
} | ||
export interface HttpParams { | ||
[key: string]: string | string[]; | ||
} | ||
export interface HttpHeaders { | ||
[key: string]: string; | ||
} | ||
export interface HttpResponse { | ||
data: any; | ||
status: number; | ||
headers: HttpHeaders; | ||
url: string; | ||
} | ||
export {}; |
import { registerPlugin } from '@capacitor/core'; | ||
const Http = registerPlugin('Http', { | ||
web: () => import('./web').then(m => new m.HttpWeb()), | ||
electron: () => window.CapacitorCustomPlatform.plugins.HTTP, | ||
}); | ||
@@ -6,0 +5,0 @@ export * from './definitions'; |
import { WebPlugin } from '@capacitor/core'; | ||
import type { HttpOptions, HttpPlugin, HttpResponse } from './definitions'; | ||
import type { HttpPlugin } from './definitions'; | ||
export declare class HttpWeb extends WebPlugin implements HttpPlugin { | ||
constructor(); | ||
/** | ||
* Perform an Http request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
request: (options: HttpOptions) => Promise<HttpResponse>; | ||
/** | ||
* Perform an Http GET request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
get: (options: HttpOptions) => Promise<HttpResponse>; | ||
/** | ||
* Perform an Http POST request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
post: (options: HttpOptions) => Promise<HttpResponse>; | ||
/** | ||
* Perform an Http PUT request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
put: (options: HttpOptions) => Promise<HttpResponse>; | ||
/** | ||
* Perform an Http PATCH request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
patch: (options: HttpOptions) => Promise<HttpResponse>; | ||
/** | ||
* Perform an Http DELETE request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
delete: (options: HttpOptions) => Promise<HttpResponse>; | ||
request(options: { | ||
value: string; | ||
}): Promise<{ | ||
value: string; | ||
}>; | ||
} | ||
export default HttpWeb; |
import { WebPlugin } from '@capacitor/core'; | ||
import * as Request from './request'; | ||
export class HttpWeb extends WebPlugin { | ||
constructor() { | ||
super(); | ||
/** | ||
* Perform an Http request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.request = async (options) => Request.request(options); | ||
/** | ||
* Perform an Http GET request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.get = async (options) => Request.request(Object.assign(Object.assign({}, options), { method: 'GET' })); | ||
/** | ||
* Perform an Http POST request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.post = async (options) => Request.request(Object.assign(Object.assign({}, options), { method: 'POST' })); | ||
/** | ||
* Perform an Http PUT request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.put = async (options) => Request.request(Object.assign(Object.assign({}, options), { method: 'PUT' })); | ||
/** | ||
* Perform an Http PATCH request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.patch = async (options) => Request.request(Object.assign(Object.assign({}, options), { method: 'PATCH' })); | ||
/** | ||
* Perform an Http DELETE request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.delete = async (options) => Request.request(Object.assign(Object.assign({}, options), { method: 'DELETE' })); | ||
async request(options) { | ||
console.log('ECHO', options); | ||
return options; | ||
} | ||
} | ||
export default HttpWeb; | ||
//# sourceMappingURL=web.js.map |
@@ -9,183 +9,8 @@ 'use strict'; | ||
web: () => Promise.resolve().then(function () { return web; }).then(m => new m.HttpWeb()), | ||
electron: () => window.CapacitorCustomPlatform.plugins.HTTP, | ||
}); | ||
/** | ||
* Read in a Blob value and return it as a base64 string | ||
* @param blob The blob value to convert to a base64 string | ||
*/ | ||
const readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => { | ||
const reader = new FileReader(); | ||
reader.onload = () => { | ||
const base64String = reader.result; | ||
const base64StringWithoutTags = base64String.substr(base64String.indexOf(',') + 1); // remove prefix "data:application/pdf;base64," | ||
resolve(base64StringWithoutTags); | ||
}; | ||
reader.onerror = (error) => reject(error); | ||
reader.readAsDataURL(blob); | ||
}); | ||
/** | ||
* Normalize an HttpHeaders map by lowercasing all of the values | ||
* @param headers The HttpHeaders object to normalize | ||
*/ | ||
const normalizeHttpHeaders = (headers = {}) => { | ||
const originalKeys = Object.keys(headers); | ||
const loweredKeys = Object.keys(headers).map(k => k.toLocaleLowerCase()); | ||
const normalized = loweredKeys.reduce((acc, key, index) => { | ||
acc[key] = headers[originalKeys[index]]; | ||
return acc; | ||
}, {}); | ||
return normalized; | ||
}; | ||
/** | ||
* Builds a string of url parameters that | ||
* @param params A map of url parameters | ||
* @param shouldEncode true if you should encodeURIComponent() the values (true by default) | ||
*/ | ||
const buildUrlParams = (params, shouldEncode = true) => { | ||
if (!params) | ||
return null; | ||
const output = Object.entries(params).reduce((accumulator, entry) => { | ||
const [key, value] = entry; | ||
let encodedValue; | ||
let item; | ||
if (Array.isArray(value)) { | ||
item = ''; | ||
value.forEach(str => { | ||
encodedValue = shouldEncode ? encodeURIComponent(str) : str; | ||
item += `${key}=${encodedValue}&`; | ||
}); | ||
// last character will always be "&" so slice it off | ||
item.slice(0, -1); | ||
} | ||
else { | ||
encodedValue = shouldEncode ? encodeURIComponent(value) : value; | ||
item = `${key}=${encodedValue}`; | ||
} | ||
return `${accumulator}&${item}`; | ||
}, ''); | ||
// Remove initial "&" from the reduce | ||
return output.substr(1); | ||
}; | ||
/** | ||
* Build the RequestInit object based on the options passed into the initial request | ||
* @param options The Http plugin options | ||
* @param extra Any extra RequestInit values | ||
*/ | ||
const buildRequestInit = (options, extra = {}) => { | ||
const output = Object.assign({ method: options.method || 'GET', headers: options.headers }, extra); | ||
// Get the content-type | ||
const headers = normalizeHttpHeaders(options.headers); | ||
const type = headers['content-type'] || ''; | ||
// If body is already a string, then pass it through as-is. | ||
if (typeof options.data === 'string') { | ||
output.body = options.data; | ||
} | ||
// Build request initializers based off of content-type | ||
else if (type.includes('application/x-www-form-urlencoded')) { | ||
const params = new URLSearchParams(); | ||
for (const [key, value] of Object.entries(options.data || {})) { | ||
params.set(key, value); | ||
} | ||
output.body = params.toString(); | ||
} | ||
else if (type.includes('multipart/form-data')) { | ||
const form = new FormData(); | ||
if (options.data instanceof FormData) { | ||
options.data.forEach((value, key) => { | ||
form.append(key, value); | ||
}); | ||
} | ||
else { | ||
for (const key of Object.keys(options.data)) { | ||
form.append(key, options.data[key]); | ||
} | ||
} | ||
output.body = form; | ||
const headers = new Headers(output.headers); | ||
headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary | ||
output.headers = headers; | ||
} | ||
else if (type.includes('application/json') || | ||
typeof options.data === 'object') { | ||
output.body = JSON.stringify(options.data); | ||
} | ||
return output; | ||
}; | ||
/** | ||
* Perform an Http request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
const request = async (options) => { | ||
const requestInit = buildRequestInit(options, options.webFetchExtra); | ||
const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams); | ||
const url = urlParams ? `${options.url}?${urlParams}` : options.url; | ||
const response = await fetch(url, requestInit); | ||
const contentType = response.headers.get('content-type') || ''; | ||
// Default to 'text' responseType so no parsing happens | ||
let { responseType = 'text' } = response.ok ? options : {}; | ||
// If the response content-type is json, force the response to be json | ||
if (contentType.includes('application/json')) { | ||
responseType = 'json'; | ||
} | ||
let data; | ||
switch (responseType) { | ||
case 'arraybuffer': | ||
case 'blob': | ||
data = await readBlobAsBase64(await response.blob()); | ||
break; | ||
case 'json': | ||
data = await response.json(); | ||
break; | ||
case 'document': | ||
case 'text': | ||
default: | ||
data = await response.text(); | ||
} | ||
// Convert fetch headers to Capacitor HttpHeaders | ||
const headers = {}; | ||
response.headers.forEach((value, key) => { | ||
headers[key] = value; | ||
}); | ||
return { | ||
data, | ||
headers, | ||
status: response.status, | ||
url: response.url, | ||
}; | ||
}; | ||
class HttpWeb extends core.WebPlugin { | ||
constructor() { | ||
super(); | ||
/** | ||
* Perform an Http request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.request = async (options) => request(options); | ||
/** | ||
* Perform an Http GET request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.get = async (options) => request(Object.assign(Object.assign({}, options), { method: 'GET' })); | ||
/** | ||
* Perform an Http POST request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.post = async (options) => request(Object.assign(Object.assign({}, options), { method: 'POST' })); | ||
/** | ||
* Perform an Http PUT request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.put = async (options) => request(Object.assign(Object.assign({}, options), { method: 'PUT' })); | ||
/** | ||
* Perform an Http PATCH request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.patch = async (options) => request(Object.assign(Object.assign({}, options), { method: 'PATCH' })); | ||
/** | ||
* Perform an Http DELETE request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.delete = async (options) => request(Object.assign(Object.assign({}, options), { method: 'DELETE' })); | ||
async request(options) { | ||
console.log('ECHO', options); | ||
return options; | ||
} | ||
@@ -196,4 +21,3 @@ } | ||
__proto__: null, | ||
HttpWeb: HttpWeb, | ||
'default': HttpWeb | ||
HttpWeb: HttpWeb | ||
}); | ||
@@ -200,0 +24,0 @@ |
@@ -6,183 +6,8 @@ var capacitorHttp = (function (exports, core) { | ||
web: () => Promise.resolve().then(function () { return web; }).then(m => new m.HttpWeb()), | ||
electron: () => window.CapacitorCustomPlatform.plugins.HTTP, | ||
}); | ||
/** | ||
* Read in a Blob value and return it as a base64 string | ||
* @param blob The blob value to convert to a base64 string | ||
*/ | ||
const readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => { | ||
const reader = new FileReader(); | ||
reader.onload = () => { | ||
const base64String = reader.result; | ||
const base64StringWithoutTags = base64String.substr(base64String.indexOf(',') + 1); // remove prefix "data:application/pdf;base64," | ||
resolve(base64StringWithoutTags); | ||
}; | ||
reader.onerror = (error) => reject(error); | ||
reader.readAsDataURL(blob); | ||
}); | ||
/** | ||
* Normalize an HttpHeaders map by lowercasing all of the values | ||
* @param headers The HttpHeaders object to normalize | ||
*/ | ||
const normalizeHttpHeaders = (headers = {}) => { | ||
const originalKeys = Object.keys(headers); | ||
const loweredKeys = Object.keys(headers).map(k => k.toLocaleLowerCase()); | ||
const normalized = loweredKeys.reduce((acc, key, index) => { | ||
acc[key] = headers[originalKeys[index]]; | ||
return acc; | ||
}, {}); | ||
return normalized; | ||
}; | ||
/** | ||
* Builds a string of url parameters that | ||
* @param params A map of url parameters | ||
* @param shouldEncode true if you should encodeURIComponent() the values (true by default) | ||
*/ | ||
const buildUrlParams = (params, shouldEncode = true) => { | ||
if (!params) | ||
return null; | ||
const output = Object.entries(params).reduce((accumulator, entry) => { | ||
const [key, value] = entry; | ||
let encodedValue; | ||
let item; | ||
if (Array.isArray(value)) { | ||
item = ''; | ||
value.forEach(str => { | ||
encodedValue = shouldEncode ? encodeURIComponent(str) : str; | ||
item += `${key}=${encodedValue}&`; | ||
}); | ||
// last character will always be "&" so slice it off | ||
item.slice(0, -1); | ||
} | ||
else { | ||
encodedValue = shouldEncode ? encodeURIComponent(value) : value; | ||
item = `${key}=${encodedValue}`; | ||
} | ||
return `${accumulator}&${item}`; | ||
}, ''); | ||
// Remove initial "&" from the reduce | ||
return output.substr(1); | ||
}; | ||
/** | ||
* Build the RequestInit object based on the options passed into the initial request | ||
* @param options The Http plugin options | ||
* @param extra Any extra RequestInit values | ||
*/ | ||
const buildRequestInit = (options, extra = {}) => { | ||
const output = Object.assign({ method: options.method || 'GET', headers: options.headers }, extra); | ||
// Get the content-type | ||
const headers = normalizeHttpHeaders(options.headers); | ||
const type = headers['content-type'] || ''; | ||
// If body is already a string, then pass it through as-is. | ||
if (typeof options.data === 'string') { | ||
output.body = options.data; | ||
} | ||
// Build request initializers based off of content-type | ||
else if (type.includes('application/x-www-form-urlencoded')) { | ||
const params = new URLSearchParams(); | ||
for (const [key, value] of Object.entries(options.data || {})) { | ||
params.set(key, value); | ||
} | ||
output.body = params.toString(); | ||
} | ||
else if (type.includes('multipart/form-data')) { | ||
const form = new FormData(); | ||
if (options.data instanceof FormData) { | ||
options.data.forEach((value, key) => { | ||
form.append(key, value); | ||
}); | ||
} | ||
else { | ||
for (const key of Object.keys(options.data)) { | ||
form.append(key, options.data[key]); | ||
} | ||
} | ||
output.body = form; | ||
const headers = new Headers(output.headers); | ||
headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary | ||
output.headers = headers; | ||
} | ||
else if (type.includes('application/json') || | ||
typeof options.data === 'object') { | ||
output.body = JSON.stringify(options.data); | ||
} | ||
return output; | ||
}; | ||
/** | ||
* Perform an Http request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
const request = async (options) => { | ||
const requestInit = buildRequestInit(options, options.webFetchExtra); | ||
const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams); | ||
const url = urlParams ? `${options.url}?${urlParams}` : options.url; | ||
const response = await fetch(url, requestInit); | ||
const contentType = response.headers.get('content-type') || ''; | ||
// Default to 'text' responseType so no parsing happens | ||
let { responseType = 'text' } = response.ok ? options : {}; | ||
// If the response content-type is json, force the response to be json | ||
if (contentType.includes('application/json')) { | ||
responseType = 'json'; | ||
} | ||
let data; | ||
switch (responseType) { | ||
case 'arraybuffer': | ||
case 'blob': | ||
data = await readBlobAsBase64(await response.blob()); | ||
break; | ||
case 'json': | ||
data = await response.json(); | ||
break; | ||
case 'document': | ||
case 'text': | ||
default: | ||
data = await response.text(); | ||
} | ||
// Convert fetch headers to Capacitor HttpHeaders | ||
const headers = {}; | ||
response.headers.forEach((value, key) => { | ||
headers[key] = value; | ||
}); | ||
return { | ||
data, | ||
headers, | ||
status: response.status, | ||
url: response.url, | ||
}; | ||
}; | ||
class HttpWeb extends core.WebPlugin { | ||
constructor() { | ||
super(); | ||
/** | ||
* Perform an Http request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.request = async (options) => request(options); | ||
/** | ||
* Perform an Http GET request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.get = async (options) => request(Object.assign(Object.assign({}, options), { method: 'GET' })); | ||
/** | ||
* Perform an Http POST request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.post = async (options) => request(Object.assign(Object.assign({}, options), { method: 'POST' })); | ||
/** | ||
* Perform an Http PUT request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.put = async (options) => request(Object.assign(Object.assign({}, options), { method: 'PUT' })); | ||
/** | ||
* Perform an Http PATCH request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.patch = async (options) => request(Object.assign(Object.assign({}, options), { method: 'PATCH' })); | ||
/** | ||
* Perform an Http DELETE request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
this.delete = async (options) => request(Object.assign(Object.assign({}, options), { method: 'DELETE' })); | ||
async request(options) { | ||
console.log('ECHO', options); | ||
return options; | ||
} | ||
@@ -193,4 +18,3 @@ } | ||
__proto__: null, | ||
HttpWeb: HttpWeb, | ||
'default': HttpWeb | ||
HttpWeb: HttpWeb | ||
}); | ||
@@ -197,0 +21,0 @@ |
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** | ||
* Read in a Blob value and return it as a base64 string | ||
* @param blob The blob value to convert to a base64 string | ||
*/ | ||
const readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => { | ||
const reader = new FileReader(); | ||
reader.onload = () => { | ||
const base64String = reader.result; | ||
const base64StringWithoutTags = base64String.substr(base64String.indexOf(',') + 1); // remove prefix "data:application/pdf;base64," | ||
resolve(base64StringWithoutTags); | ||
}; | ||
reader.onerror = (error) => reject(error); | ||
reader.readAsDataURL(blob); | ||
}); | ||
/** | ||
* Normalize an HttpHeaders map by lowercasing all of the values | ||
* @param headers The HttpHeaders object to normalize | ||
*/ | ||
const normalizeHttpHeaders = (headers = {}) => { | ||
const originalKeys = Object.keys(headers); | ||
const loweredKeys = Object.keys(headers).map(k => k.toLocaleLowerCase()); | ||
const normalized = loweredKeys.reduce((acc, key, index) => { | ||
acc[key] = headers[originalKeys[index]]; | ||
return acc; | ||
}, {}); | ||
return normalized; | ||
}; | ||
/** | ||
* Builds a string of url parameters that | ||
* @param params A map of url parameters | ||
* @param shouldEncode true if you should encodeURIComponent() the values (true by default) | ||
*/ | ||
const buildUrlParams = (params, shouldEncode = true) => { | ||
if (!params) | ||
return null; | ||
const output = Object.entries(params).reduce((accumulator, entry) => { | ||
const [key, value] = entry; | ||
let encodedValue; | ||
let item; | ||
if (Array.isArray(value)) { | ||
item = ''; | ||
value.forEach(str => { | ||
encodedValue = shouldEncode ? encodeURIComponent(str) : str; | ||
item += `${key}=${encodedValue}&`; | ||
}); | ||
// last character will always be "&" so slice it off | ||
item.slice(0, -1); | ||
} | ||
else { | ||
encodedValue = shouldEncode ? encodeURIComponent(value) : value; | ||
item = `${key}=${encodedValue}`; | ||
} | ||
return `${accumulator}&${item}`; | ||
}, ''); | ||
// Remove initial "&" from the reduce | ||
return output.substr(1); | ||
}; | ||
/** | ||
* Build the RequestInit object based on the options passed into the initial request | ||
* @param options The Http plugin options | ||
* @param extra Any extra RequestInit values | ||
*/ | ||
const buildRequestInit = (options, extra = {}) => { | ||
const output = Object.assign({ method: options.method || 'GET', headers: options.headers }, extra); | ||
// Get the content-type | ||
const headers = normalizeHttpHeaders(options.headers); | ||
const type = headers['content-type'] || ''; | ||
// If body is already a string, then pass it through as-is. | ||
if (typeof options.data === 'string') { | ||
output.body = options.data; | ||
exports.HttpWeb = void 0; | ||
const core_1 = require("@capacitor/core"); | ||
class HttpWeb extends core_1.WebPlugin { | ||
async request(options) { | ||
console.log('ECHO', options); | ||
return options; | ||
} | ||
// Build request initializers based off of content-type | ||
else if (type.includes('application/x-www-form-urlencoded')) { | ||
const params = new URLSearchParams(); | ||
for (const [key, value] of Object.entries(options.data || {})) { | ||
params.set(key, value); | ||
} | ||
output.body = params.toString(); | ||
} | ||
else if (type.includes('multipart/form-data')) { | ||
const form = new FormData(); | ||
if (options.data instanceof FormData) { | ||
options.data.forEach((value, key) => { | ||
form.append(key, value); | ||
}); | ||
} | ||
else { | ||
for (const key of Object.keys(options.data)) { | ||
form.append(key, options.data[key]); | ||
} | ||
} | ||
output.body = form; | ||
const headers = new Headers(output.headers); | ||
headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary | ||
output.headers = headers; | ||
} | ||
else if (type.includes('application/json') || | ||
typeof options.data === 'object') { | ||
output.body = JSON.stringify(options.data); | ||
} | ||
return output; | ||
}; | ||
/** | ||
* Perform an Http request given a set of options | ||
* @param options Options to build the HTTP request | ||
*/ | ||
const request = async (options) => { | ||
const requestInit = buildRequestInit(options, options.webFetchExtra); | ||
const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams); | ||
const url = urlParams ? `${options.url}?${urlParams}` : options.url; | ||
const response = await fetch(url, requestInit); | ||
const contentType = response.headers.get('content-type') || ''; | ||
// Default to 'text' responseType so no parsing happens | ||
let { responseType = 'text' } = response.ok ? options : {}; | ||
// If the response content-type is json, force the response to be json | ||
if (contentType.includes('application/json')) { | ||
responseType = 'json'; | ||
} | ||
let data; | ||
switch (responseType) { | ||
case 'arraybuffer': | ||
case 'blob': | ||
data = await readBlobAsBase64(await response.blob()); | ||
break; | ||
case 'json': | ||
data = await response.json(); | ||
break; | ||
case 'document': | ||
case 'text': | ||
default: | ||
data = await response.text(); | ||
} | ||
// Convert fetch headers to Capacitor HttpHeaders | ||
const headers = {}; | ||
response.headers.forEach((value, key) => { | ||
headers[key] = value; | ||
}); | ||
return { | ||
data, | ||
headers, | ||
status: response.status, | ||
url: response.url, | ||
}; | ||
}; | ||
class HttpElectron { | ||
request(options) { | ||
return request(options); | ||
} | ||
get(options) { | ||
return request(Object.assign(Object.assign({}, options), { method: 'GET' })); | ||
} | ||
post(options) { | ||
return request(Object.assign(Object.assign({}, options), { method: 'POST' })); | ||
} | ||
put(options) { | ||
return request(Object.assign(Object.assign({}, options), { method: 'PUT' })); | ||
} | ||
patch(options) { | ||
return request(Object.assign(Object.assign({}, options), { method: 'PATCH' })); | ||
} | ||
delete(options) { | ||
return request(Object.assign(Object.assign({}, options), { method: 'DELETE' })); | ||
} | ||
} | ||
exports.default = HttpElectron; | ||
exports.HttpWeb = HttpWeb; | ||
//# sourceMappingURL=plugin.js.map |
@@ -8,3 +8,3 @@ export default { | ||
sourcemap: true, | ||
inlineDynamicImports: true | ||
inlineDynamicImports: true, | ||
}, | ||
@@ -11,0 +11,0 @@ ], |
{ | ||
"name": "@minotaur-ergo/http", | ||
"version": "0.0.7", | ||
"version": "0.0.8", | ||
"description": "Cors Free Http Client", | ||
@@ -21,6 +21,6 @@ "main": "dist/plugin.cjs.js", | ||
"type": "git", | ||
"url": "git+https://github.com/minotaur-ergo/http.git" | ||
"url": "git+https://github.com/minotaur-ergo/http-plugin.git" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/minotaur-ergo/http/issues" | ||
"url": "https://github.com/minotaur-ergo/http-plugin/issues" | ||
}, | ||
@@ -27,0 +27,0 @@ "keywords": [ |
137
README.md
@@ -17,9 +17,2 @@ # @minotaur-ergo/http | ||
* [`request(...)`](#request) | ||
* [`get(...)`](#get) | ||
* [`post(...)`](#post) | ||
* [`put(...)`](#put) | ||
* [`patch(...)`](#patch) | ||
* [`delete(...)`](#delete) | ||
* [Interfaces](#interfaces) | ||
* [Type Aliases](#type-aliases) | ||
@@ -34,133 +27,13 @@ </docgen-index> | ||
```typescript | ||
request(options: HttpOptions) => Promise<HttpResponse> | ||
request(options: { value: string; }) => Promise<{ value: string; }> | ||
``` | ||
| Param | Type | | ||
| ------------- | --------------------------------------------------- | | ||
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> | | ||
| Param | Type | | ||
| ------------- | ------------------------------- | | ||
| **`options`** | <code>{ value: string; }</code> | | ||
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code> | ||
**Returns:** <code>Promise<{ value: string; }></code> | ||
-------------------- | ||
### get(...) | ||
```typescript | ||
get(options: HttpOptions) => Promise<HttpResponse> | ||
``` | ||
| Param | Type | | ||
| ------------- | --------------------------------------------------- | | ||
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> | | ||
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code> | ||
-------------------- | ||
### post(...) | ||
```typescript | ||
post(options: HttpOptions) => Promise<HttpResponse> | ||
``` | ||
| Param | Type | | ||
| ------------- | --------------------------------------------------- | | ||
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> | | ||
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code> | ||
-------------------- | ||
### put(...) | ||
```typescript | ||
put(options: HttpOptions) => Promise<HttpResponse> | ||
``` | ||
| Param | Type | | ||
| ------------- | --------------------------------------------------- | | ||
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> | | ||
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code> | ||
-------------------- | ||
### patch(...) | ||
```typescript | ||
patch(options: HttpOptions) => Promise<HttpResponse> | ||
``` | ||
| Param | Type | | ||
| ------------- | --------------------------------------------------- | | ||
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> | | ||
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code> | ||
-------------------- | ||
### delete(...) | ||
```typescript | ||
delete(options: HttpOptions) => Promise<HttpResponse> | ||
``` | ||
| Param | Type | | ||
| ------------- | --------------------------------------------------- | | ||
| **`options`** | <code><a href="#httpoptions">HttpOptions</a></code> | | ||
**Returns:** <code>Promise<<a href="#httpresponse">HttpResponse</a>></code> | ||
-------------------- | ||
### Interfaces | ||
#### HttpResponse | ||
| Prop | Type | | ||
| ------------- | --------------------------------------------------- | | ||
| **`data`** | <code>any</code> | | ||
| **`status`** | <code>number</code> | | ||
| **`headers`** | <code><a href="#httpheaders">HttpHeaders</a></code> | | ||
| **`url`** | <code>string</code> | | ||
#### HttpHeaders | ||
#### HttpOptions | ||
| Prop | Type | Description | | ||
| --------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| **`url`** | <code>string</code> | | | ||
| **`method`** | <code>string</code> | | | ||
| **`params`** | <code><a href="#httpparams">HttpParams</a></code> | | | ||
| **`data`** | <code>any</code> | Note: On Android and iOS, data can only be a string or a JSON. FormData, Blob, ArrayBuffer, and other complex types are only directly supported on web or through enabling `CapacitorHttp` in the config and using the patched `window.fetch` or `XMLHttpRequest`. If you need to send a complex type, you should serialize the data to base64 and set the `headers["Content-Type"]` and `dataType` attributes accordingly. | | ||
| **`headers`** | <code><a href="#httpheaders">HttpHeaders</a></code> | | | ||
| **`readTimeout`** | <code>number</code> | How long to wait to read additional data. Resets each time new data is received | | ||
| **`connectTimeout`** | <code>number</code> | How long to wait for the initial connection. | | ||
| **`disableRedirects`** | <code>boolean</code> | Sets whether automatic HTTP redirects should be disabled | | ||
| **`webFetchExtra`** | <code>RequestInit</code> | Extra arguments for fetch when running on the web | | ||
| **`responseType`** | <code><a href="#httpresponsetype">HttpResponseType</a></code> | This is used to parse the response appropriately before returning it to the requestee. If the response content-type is "json", this value is ignored. | | ||
| **`shouldEncodeUrlParams`** | <code>boolean</code> | Use this option if you need to keep the URL unencoded in certain cases (already encoded, azure/firebase testing, etc.). The default is _true_. | | ||
| **`dataType`** | <code>'file' \| 'formData'</code> | This is used if we've had to convert the data from a JS type that needs special handling in the native layer | | ||
#### HttpParams | ||
### Type Aliases | ||
#### HttpResponseType | ||
<code>'arraybuffer' | 'blob' | 'json' | 'text' | 'document'</code> | ||
</docgen-api> |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
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
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
1
16985
31
143
1
38