Refactor Code to typescript
This commit is contained in:
-7
@@ -1,7 +0,0 @@
|
||||
declare function _exports({ clientId, redirectUrl, setLoading, scopes }: {
|
||||
clientId: string;
|
||||
redirectUrl: string;
|
||||
setLoading?: (arg0: boolean) => void;
|
||||
scopes?: string[];
|
||||
}): void;
|
||||
export = _exports;
|
||||
@@ -1,36 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Login with Github Function
|
||||
* ===============================================================================
|
||||
* @description This function uses github api to login a user with datasquirel
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single object passed
|
||||
* @param {string} params.clientId - Github app client ID: {@link https://datasquirel.com/docs}
|
||||
* @param {string} params.redirectUrl - Github Redirect URL as listed in your oauth app settings: {@link https://datasquirel.com/docs}
|
||||
* @param {function(boolean): void} [params.setLoading] - React setState Function: sets whether the google login button is ready or not
|
||||
* @param {string[]} [params.scopes] - Scopes to be requested from the user
|
||||
*
|
||||
* @returns {void} - Return
|
||||
*/
|
||||
module.exports = function getAccessToken({ clientId, redirectUrl, setLoading, scopes }) {
|
||||
/**
|
||||
* == Initialize
|
||||
*
|
||||
* @description Initialize
|
||||
*/
|
||||
if (setLoading) setLoading(true);
|
||||
|
||||
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
||||
const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`;
|
||||
window.location.assign(fetchUrl);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
type Param = {
|
||||
clientId: string;
|
||||
redirectUrl: string;
|
||||
setLoading?: (arg0: boolean) => void;
|
||||
scopes?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Login with Github Function
|
||||
* ===============================================================================
|
||||
* @description This function uses github api to login a user with datasquirel
|
||||
*/
|
||||
export default function getAccessToken({
|
||||
clientId,
|
||||
redirectUrl,
|
||||
setLoading,
|
||||
scopes,
|
||||
}: Param): void {
|
||||
if (setLoading) setLoading(true);
|
||||
|
||||
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
||||
const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`;
|
||||
window.location.assign(fetchUrl);
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
declare namespace _exports {
|
||||
export { GoogleGetAccessTokenFunctionParams };
|
||||
}
|
||||
declare function _exports(params: GoogleGetAccessTokenFunctionParams): Promise<string>;
|
||||
export = _exports;
|
||||
type GoogleGetAccessTokenFunctionParams = {
|
||||
/**
|
||||
* - Google app client ID: {@link https://datasquirel.com/docs}
|
||||
*/
|
||||
clientId: string;
|
||||
/**
|
||||
* - Whether to trigger Google signing popup or not: {@link https://datasquirel.com/docs}
|
||||
*/
|
||||
triggerPrompt?: boolean;
|
||||
/**
|
||||
* - React setState Function: sets whether the google login button is ready or not
|
||||
*/
|
||||
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
};
|
||||
@@ -1,33 +1,22 @@
|
||||
// @ts-check
|
||||
interface GoogleGetAccessTokenFunctionParams {
|
||||
clientId: string;
|
||||
triggerPrompt?: boolean;
|
||||
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} GoogleGetAccessTokenFunctionParams
|
||||
* @property {string} clientId - Google app client ID: {@link https://datasquirel.com/docs}
|
||||
* @property {boolean} [triggerPrompt] - Whether to trigger Google signing popup or not: {@link https://datasquirel.com/docs}
|
||||
* @property {React.Dispatch<React.SetStateAction<boolean>>} [setLoading] - React setState Function: sets whether the google login button is ready or not
|
||||
*
|
||||
*/
|
||||
|
||||
/** @type {any} */
|
||||
let interval;
|
||||
let interval: any;
|
||||
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @requires script "https://accounts.google.com/gsi/client" async script added to head
|
||||
*
|
||||
* @param {GoogleGetAccessTokenFunctionParams} params - Single object passed
|
||||
|
||||
* @returns {Promise<string>} - Access Token String
|
||||
*/
|
||||
module.exports = async function getAccessToken(params) {
|
||||
export default async function getAccessToken(
|
||||
params: GoogleGetAccessTokenFunctionParams
|
||||
): Promise<string> {
|
||||
params.setLoading?.(true);
|
||||
|
||||
const response = await new Promise((resolve, reject) => {
|
||||
const response = (await new Promise((resolve, reject) => {
|
||||
interval = setInterval(() => {
|
||||
// @ts-ignore
|
||||
let google = window.google;
|
||||
@@ -37,20 +26,22 @@ module.exports = async function getAccessToken(params) {
|
||||
resolve(googleLogin({ ...params, google }));
|
||||
}
|
||||
}, 500);
|
||||
});
|
||||
})) as any;
|
||||
|
||||
params.setLoading?.(false);
|
||||
|
||||
return response;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* # Google Login Function
|
||||
*
|
||||
* @param {GoogleGetAccessTokenFunctionParams & { google: any }} params
|
||||
* @returns
|
||||
*/
|
||||
function googleLogin({ google, clientId, setLoading, triggerPrompt }) {
|
||||
export function googleLogin({
|
||||
google,
|
||||
clientId,
|
||||
setLoading,
|
||||
triggerPrompt,
|
||||
}: GoogleGetAccessTokenFunctionParams & { google: any }) {
|
||||
setTimeout(() => {
|
||||
setLoading?.(false);
|
||||
}, 3000);
|
||||
@@ -60,7 +51,9 @@ function googleLogin({ google, clientId, setLoading, triggerPrompt }) {
|
||||
* # Callback Function
|
||||
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
|
||||
*/
|
||||
function handleCredentialResponse(response) {
|
||||
function handleCredentialResponse(
|
||||
response: import("../../../package-shared/types").GoogleAccessTokenObject
|
||||
) {
|
||||
resolve(response.access_token);
|
||||
}
|
||||
|
||||
@@ -81,7 +74,9 @@ function googleLogin({ google, clientId, setLoading, triggerPrompt }) {
|
||||
* ========================================================
|
||||
* @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification
|
||||
*/
|
||||
function triggerGooglePromptCallback(notification) {
|
||||
function triggerGooglePromptCallback(
|
||||
notification: import("../../../package-shared/types").GoogleIdentityPromptNotification
|
||||
) {
|
||||
console.log(notification);
|
||||
}
|
||||
});
|
||||
Vendored
-2
@@ -1,2 +0,0 @@
|
||||
declare function _exports(params: object | null): Promise<boolean>;
|
||||
export = _exports;
|
||||
@@ -1,146 +0,0 @@
|
||||
/**
|
||||
* Type Definitions
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
const parseClientCookies = require("../utils/parseClientCookies");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object|null} params - Single object passed
|
||||
* @param {string|null} params.googleClientId - Google client Id if applicable
|
||||
*
|
||||
* @requires localStorageUser - a "user" JSON string stored in local storage with all
|
||||
* the necessary user data gotten from the server
|
||||
*
|
||||
* @returns {Promise<boolean>} - Return
|
||||
*/
|
||||
module.exports = async function logout(params) {
|
||||
/**
|
||||
* == Initialize
|
||||
*
|
||||
* @description Initialize
|
||||
*/
|
||||
const localUser = localStorage.getItem("user");
|
||||
let targetUser;
|
||||
|
||||
try {
|
||||
targetUser = JSON.parse(localUser);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
if (!targetUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const cookies = parseClientCookies();
|
||||
const socialId = cookies?.datasquirel_social_id && typeof cookies.datasquirel_social_id == "string" && !cookies.datasquirel_social_id.match(/^null$/i) ? cookies.datasquirel_social_id : null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
localStorage.setItem("user", "{}");
|
||||
localStorage.removeItem("csrf");
|
||||
|
||||
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const response = await new Promise((resolve, reject) => {
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
if (socialId && !socialId?.match(/^null$/i)) {
|
||||
const googleClientId = params?.googleClientId;
|
||||
|
||||
if (googleClientId) {
|
||||
const googleScript = document.createElement("script");
|
||||
googleScript.src = "https://accounts.google.com/gsi/client";
|
||||
googleScript.className = "social-script-tag";
|
||||
|
||||
document.body.appendChild(googleScript);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
googleScript.onload = function (e) {
|
||||
if (google) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
google.accounts.id.initialize({
|
||||
client_id: googleClientId,
|
||||
});
|
||||
|
||||
google.accounts.id.revoke(socialId, (done) => {
|
||||
console.log(done.error);
|
||||
|
||||
resolve(true);
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
};
|
||||
} else {
|
||||
resolve(true);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} else {
|
||||
resolve(true);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
});
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
return response;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
import parseClientCookies from "../utils/parseClientCookies";
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*/
|
||||
export default async function logout(
|
||||
params: { [s: string]: any } | null
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const localUser = localStorage.getItem("user");
|
||||
let targetUser;
|
||||
|
||||
try {
|
||||
targetUser = JSON.parse(localUser || "");
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
if (!targetUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const cookies = parseClientCookies();
|
||||
const socialId =
|
||||
cookies?.datasquirel_social_id &&
|
||||
typeof cookies.datasquirel_social_id == "string" &&
|
||||
!cookies.datasquirel_social_id.match(/^null$/i)
|
||||
? cookies.datasquirel_social_id
|
||||
: null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
localStorage.setItem("user", "{}");
|
||||
localStorage.removeItem("csrf");
|
||||
|
||||
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const response: boolean = await new Promise((resolve, reject) => {
|
||||
if (socialId && !socialId?.match(/^null$/i)) {
|
||||
const googleClientId = params?.googleClientId;
|
||||
|
||||
if (googleClientId) {
|
||||
const googleScript = document.createElement("script");
|
||||
googleScript.src = "https://accounts.google.com/gsi/client";
|
||||
googleScript.className = "social-script-tag";
|
||||
|
||||
document.body.appendChild(googleScript);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
googleScript.onload = function (e) {
|
||||
// @ts-ignore
|
||||
const google = window.google;
|
||||
|
||||
if (google) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
google.accounts.id.initialize({
|
||||
client_id: googleClientId,
|
||||
});
|
||||
|
||||
google.accounts.id.revoke(socialId, (done: any) => {
|
||||
console.log(done.error);
|
||||
resolve(true);
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
};
|
||||
} else {
|
||||
resolve(true);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} else {
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Vendored
-5
@@ -1,5 +0,0 @@
|
||||
export = clientFetch;
|
||||
declare function clientFetch(url: string, options?: import("../../package-shared/types").FetchApiOptions, csrf?: boolean): Promise<any>;
|
||||
declare namespace clientFetch {
|
||||
export { clientFetch as fetchApi };
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
|
||||
/** @type {import("../../package-shared/types").FetchApiFn} */
|
||||
async function clientFetch(url, options, csrf) {
|
||||
let data;
|
||||
let finalUrl = url;
|
||||
|
||||
if (typeof options === "string") {
|
||||
try {
|
||||
let fetchData;
|
||||
|
||||
switch (options) {
|
||||
case "post":
|
||||
fetchData = await fetch(finalUrl, {
|
||||
method: options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
data = await fetchData.json();
|
||||
break;
|
||||
|
||||
default:
|
||||
fetchData = await fetch(finalUrl);
|
||||
data = await fetchData.json();
|
||||
break;
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("FetchAPI error #1:", error.message);
|
||||
data = null;
|
||||
}
|
||||
} else if (typeof options === "object") {
|
||||
try {
|
||||
let fetchData;
|
||||
|
||||
if (options.query) {
|
||||
let pathSuffix = "";
|
||||
pathSuffix += "?";
|
||||
const queryString = Object.keys(options.query)
|
||||
?.map((queryKey) => {
|
||||
if (!options.query?.[queryKey]) return undefined;
|
||||
if (typeof options.query[queryKey] == "object") {
|
||||
return `${queryKey}=${JSON.stringify(
|
||||
options.query[queryKey]
|
||||
)}`;
|
||||
}
|
||||
return `${queryKey}=${options.query[queryKey]}`;
|
||||
})
|
||||
.filter((prt) => prt)
|
||||
.join("&");
|
||||
pathSuffix += queryString;
|
||||
finalUrl += pathSuffix;
|
||||
delete options.query;
|
||||
}
|
||||
|
||||
if (options.body && typeof options.body === "object") {
|
||||
let oldOptionsBody = _.cloneDeep(options.body);
|
||||
options.body = JSON.stringify(oldOptionsBody);
|
||||
}
|
||||
|
||||
if (options.headers) {
|
||||
/** @type {any} */
|
||||
const finalOptions = { ...options };
|
||||
|
||||
fetchData = await fetch(finalUrl, finalOptions);
|
||||
} else {
|
||||
fetchData = await fetch(finalUrl, {
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
data = await fetchData.json();
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("FetchAPI error #2:", error.message);
|
||||
data = null;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
let fetchData = await fetch(finalUrl);
|
||||
data = await fetchData.json();
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("FetchAPI error #3:", error.message);
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
module.exports = clientFetch;
|
||||
exports.fetchApi = clientFetch;
|
||||
@@ -0,0 +1,113 @@
|
||||
import _ from "lodash";
|
||||
|
||||
type FetchApiOptions = {
|
||||
method:
|
||||
| "POST"
|
||||
| "GET"
|
||||
| "DELETE"
|
||||
| "PUT"
|
||||
| "PATCH"
|
||||
| "post"
|
||||
| "get"
|
||||
| "delete"
|
||||
| "put"
|
||||
| "patch";
|
||||
body?: object | string;
|
||||
headers?: FetchHeader;
|
||||
};
|
||||
|
||||
type FetchHeader = HeadersInit & {
|
||||
[key: string]: string | null;
|
||||
};
|
||||
|
||||
export type FetchApiReturn = {
|
||||
success: boolean;
|
||||
payload: any;
|
||||
msg?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Fetch API
|
||||
*/
|
||||
export default async function fetchApi(
|
||||
url: string,
|
||||
options?: FetchApiOptions,
|
||||
csrf?: boolean,
|
||||
/** Key to use to grab local Storage csrf value. */
|
||||
localStorageCSRFKey?: string
|
||||
): Promise<any> {
|
||||
let data;
|
||||
|
||||
const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf");
|
||||
|
||||
let finalHeaders = {
|
||||
"Content-Type": "application/json",
|
||||
} as FetchHeader;
|
||||
|
||||
if (csrf && csrfValue) {
|
||||
finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true";
|
||||
}
|
||||
|
||||
if (typeof options === "string") {
|
||||
try {
|
||||
let fetchData;
|
||||
|
||||
switch (options) {
|
||||
case "post":
|
||||
fetchData = await fetch(url, {
|
||||
method: options,
|
||||
headers: finalHeaders,
|
||||
} as RequestInit);
|
||||
data = fetchData.json();
|
||||
break;
|
||||
|
||||
default:
|
||||
fetchData = await fetch(url);
|
||||
data = fetchData.json();
|
||||
break;
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log("FetchAPI error #1:", error.message);
|
||||
data = null;
|
||||
}
|
||||
} else if (typeof options === "object") {
|
||||
try {
|
||||
let fetchData;
|
||||
|
||||
if (options.body && typeof options.body === "object") {
|
||||
let oldOptionsBody = _.cloneDeep(options.body);
|
||||
options.body = JSON.stringify(oldOptionsBody);
|
||||
}
|
||||
|
||||
if (options.headers) {
|
||||
options.headers = _.merge(options.headers, finalHeaders);
|
||||
|
||||
const finalOptions: any = { ...options };
|
||||
fetchData = await fetch(url, finalOptions);
|
||||
} else {
|
||||
const finalOptions = {
|
||||
...options,
|
||||
headers: finalHeaders,
|
||||
} as RequestInit;
|
||||
|
||||
fetchData = await fetch(url, finalOptions);
|
||||
}
|
||||
|
||||
data = fetchData.json();
|
||||
} catch (error: any) {
|
||||
console.log("FetchAPI error #2:", error.message);
|
||||
data = null;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
let fetchData = await fetch(url);
|
||||
data = await fetchData.json();
|
||||
} catch (error: any) {
|
||||
console.log("FetchAPI error #3:", error.message);
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
Vendored
-38
@@ -1,38 +0,0 @@
|
||||
export namespace media {
|
||||
export { imageInputToBase64 };
|
||||
export { imageInputFileToBase64 };
|
||||
export { inputFileToBase64 };
|
||||
}
|
||||
export namespace auth {
|
||||
export namespace google {
|
||||
export { getAccessToken };
|
||||
}
|
||||
export namespace github {
|
||||
export { getGithubAccessToken as getAccessToken };
|
||||
}
|
||||
export { logout };
|
||||
}
|
||||
export namespace fetch {
|
||||
export { fetchApi };
|
||||
export { clientFetch };
|
||||
}
|
||||
export namespace utils {
|
||||
export { serializeQuery };
|
||||
export { serializeCookies };
|
||||
export { EJSON };
|
||||
export { numberfy };
|
||||
export { slugify };
|
||||
}
|
||||
import imageInputToBase64 = require("./media/imageInputToBase64");
|
||||
import imageInputFileToBase64 = require("./media/imageInputFileToBase64");
|
||||
import inputFileToBase64 = require("./media/inputFileToBase64");
|
||||
import getAccessToken = require("./auth/google/getAccessToken");
|
||||
import getGithubAccessToken = require("./auth/github/getAccessToken");
|
||||
import logout = require("./auth/logout");
|
||||
import { fetchApi } from "./fetch";
|
||||
import clientFetch = require("./fetch");
|
||||
import serializeQuery = require("../package-shared/utils/serialize-query");
|
||||
import serializeCookies = require("../package-shared/utils/serialize-cookies");
|
||||
import EJSON = require("../package-shared/utils/ejson");
|
||||
import numberfy = require("../package-shared/utils/numberfy");
|
||||
import slugify = require("../package-shared/utils/slugify");
|
||||
@@ -1,67 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Imports
|
||||
*/
|
||||
const imageInputFileToBase64 = require("./media/imageInputFileToBase64");
|
||||
const imageInputToBase64 = require("./media/imageInputToBase64");
|
||||
const inputFileToBase64 = require("./media/inputFileToBase64");
|
||||
const getAccessToken = require("./auth/google/getAccessToken");
|
||||
const getGithubAccessToken = require("./auth/github/getAccessToken");
|
||||
const logout = require("./auth/logout");
|
||||
const { fetchApi } = require("./fetch");
|
||||
const clientFetch = require("./fetch");
|
||||
const serializeQuery = require("../package-shared/utils/serialize-query");
|
||||
const serializeCookies = require("../package-shared/utils/serialize-cookies");
|
||||
const EJSON = require("../package-shared/utils/ejson");
|
||||
const numberfy = require("../package-shared/utils/numberfy");
|
||||
const slugify = require("../package-shared/utils/slugify");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Media Functions Object
|
||||
*/
|
||||
const media = {
|
||||
imageInputToBase64: imageInputToBase64,
|
||||
imageInputFileToBase64: imageInputFileToBase64,
|
||||
inputFileToBase64: inputFileToBase64,
|
||||
};
|
||||
|
||||
/**
|
||||
* User Auth Object
|
||||
*/
|
||||
const auth = {
|
||||
google: {
|
||||
getAccessToken: getAccessToken,
|
||||
},
|
||||
github: {
|
||||
getAccessToken: getGithubAccessToken,
|
||||
},
|
||||
logout: logout,
|
||||
};
|
||||
|
||||
const utils = {
|
||||
serializeQuery,
|
||||
serializeCookies,
|
||||
EJSON,
|
||||
numberfy,
|
||||
slugify,
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch
|
||||
*/
|
||||
const fetch = {
|
||||
fetchApi,
|
||||
clientFetch,
|
||||
};
|
||||
|
||||
/**
|
||||
* Main Export
|
||||
*/
|
||||
const datasquirelClient = { media, auth, fetch, utils };
|
||||
|
||||
module.exports = datasquirelClient;
|
||||
@@ -0,0 +1,62 @@
|
||||
import imageInputFileToBase64 from "./media/imageInputFileToBase64";
|
||||
import imageInputToBase64 from "./media/imageInputToBase64";
|
||||
import inputFileToBase64 from "./media/inputFileToBase64";
|
||||
import getAccessToken from "./auth/google/getAccessToken";
|
||||
import getGithubAccessToken from "./auth/github/getAccessToken";
|
||||
import logout from "./auth/logout";
|
||||
import fetchApi from "./fetch";
|
||||
import clientFetch from "./fetch";
|
||||
import serializeQuery from "../package-shared/utils/serialize-query";
|
||||
import serializeCookies from "../package-shared/utils/serialize-cookies";
|
||||
import EJSON from "../package-shared/utils/ejson";
|
||||
import numberfy from "../package-shared/utils/numberfy";
|
||||
import slugify from "../package-shared/utils/slugify";
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Media Functions Object
|
||||
*/
|
||||
const media = {
|
||||
imageInputToBase64: imageInputToBase64,
|
||||
imageInputFileToBase64: imageInputFileToBase64,
|
||||
inputFileToBase64: inputFileToBase64,
|
||||
};
|
||||
|
||||
/**
|
||||
* User Auth Object
|
||||
*/
|
||||
const auth = {
|
||||
google: {
|
||||
getAccessToken: getAccessToken,
|
||||
},
|
||||
github: {
|
||||
getAccessToken: getGithubAccessToken,
|
||||
},
|
||||
logout: logout,
|
||||
};
|
||||
|
||||
const utils = {
|
||||
serializeQuery,
|
||||
serializeCookies,
|
||||
EJSON,
|
||||
numberfy,
|
||||
slugify,
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch
|
||||
*/
|
||||
const fetch = {
|
||||
fetchApi,
|
||||
clientFetch,
|
||||
};
|
||||
|
||||
/**
|
||||
* Main Export
|
||||
*/
|
||||
const datasquirelClient = { media, auth, fetch, utils };
|
||||
|
||||
export default datasquirelClient;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
declare function _exports({ imageInputFile, maxWidth, imagePreviewNode, }: {
|
||||
imageInputFile: {
|
||||
name: string;
|
||||
};
|
||||
maxWidth?: number;
|
||||
imagePreviewNode?: HTMLImageElement;
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
@@ -1,22 +1,19 @@
|
||||
import { ImageInputFileToBase64FunctionReturn } from "../../package-shared/types";
|
||||
|
||||
type Param = {
|
||||
imageInputFile: File;
|
||||
maxWidth?: number;
|
||||
imagePreviewNode?: HTMLImageElement;
|
||||
};
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {{
|
||||
* imageInputFile: { name:string },
|
||||
* maxWidth?: number,
|
||||
* imagePreviewNode?: HTMLImageElement,
|
||||
* }} params - Single object passed
|
||||
*
|
||||
* @returns { Promise<import("../../types/general.td").ImageInputFileToBase64FunctionReturn> } - Return Object
|
||||
* # Image input File top Base64
|
||||
*/
|
||||
module.exports = async function imageInputFileToBase64({
|
||||
export default async function imageInputFileToBase64({
|
||||
imageInputFile,
|
||||
maxWidth,
|
||||
imagePreviewNode,
|
||||
}) {
|
||||
}: Param): Promise<ImageInputFileToBase64FunctionReturn> {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
@@ -24,15 +21,15 @@ module.exports = async function imageInputFileToBase64({
|
||||
*/
|
||||
try {
|
||||
let imageName = imageInputFile.name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
let imageSize;
|
||||
let imageDataBase64: string | undefined;
|
||||
let imageSize: number | undefined;
|
||||
let canvas = document.createElement("canvas");
|
||||
|
||||
const MIME_TYPE = imageInputFile.type;
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
|
||||
const file = imageInputFile; // get the file
|
||||
const file = imageInputFile;
|
||||
const blobURL = URL.createObjectURL(file);
|
||||
const img = new Image();
|
||||
|
||||
@@ -47,8 +44,9 @@ module.exports = async function imageInputFileToBase64({
|
||||
};
|
||||
|
||||
/** ********************* Handle new image when loaded */
|
||||
img.onload = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target as HTMLImageElement;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
@@ -67,7 +65,7 @@ module.exports = async function imageInputFileToBase64({
|
||||
}
|
||||
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
|
||||
@@ -82,7 +80,7 @@ module.exports = async function imageInputFileToBase64({
|
||||
imageSize = await new Promise((res, rej) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
res(blob.size);
|
||||
res(blob?.size);
|
||||
},
|
||||
MIME_TYPE,
|
||||
QUALITY
|
||||
@@ -90,23 +88,19 @@ module.exports = async function imageInputFileToBase64({
|
||||
});
|
||||
|
||||
return {
|
||||
imageBase64: imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64: imageDataBase64?.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
imageSize: imageSize,
|
||||
};
|
||||
} catch (/** @type {*} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
|
||||
return {
|
||||
imageBase64: null,
|
||||
imageBase64Full: null,
|
||||
imageName: null,
|
||||
imageSize: null,
|
||||
imageBase64: undefined,
|
||||
imageBase64Full: undefined,
|
||||
imageName: undefined,
|
||||
imageSize: undefined,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
}
|
||||
Vendored
-14
@@ -1,14 +0,0 @@
|
||||
declare namespace _exports {
|
||||
export { FunctionReturn };
|
||||
}
|
||||
declare function _exports({ imageInput, maxWidth, mimeType, }: {
|
||||
imageInput: HTMLInputElement;
|
||||
maxWidth?: number;
|
||||
mimeType?: [string];
|
||||
}): Promise<FunctionReturn>;
|
||||
export = _exports;
|
||||
type FunctionReturn = {
|
||||
imageBase64: string;
|
||||
imageBase64Full: string;
|
||||
imageName: string;
|
||||
};
|
||||
@@ -1,115 +0,0 @@
|
||||
/**
|
||||
* @typedef {{
|
||||
* imageBase64: string,
|
||||
* imageBase64Full: string,
|
||||
* imageName: string,
|
||||
* }} FunctionReturn
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {{
|
||||
* imageInput: HTMLInputElement,
|
||||
* maxWidth?: number,
|
||||
* mimeType?: [string='image/jpeg']
|
||||
* }} params - Single object passed
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> } - Return Object
|
||||
*/
|
||||
module.exports = async function imageInputToBase64({
|
||||
imageInput,
|
||||
maxWidth,
|
||||
mimeType,
|
||||
}) {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imagePreviewNode = document.querySelector(
|
||||
`[data-imagepreview='image']`
|
||||
);
|
||||
let imageName = imageInput.files[0].name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
|
||||
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
|
||||
const file = imageInput.files[0]; // get the file
|
||||
const blobURL = URL.createObjectURL(file);
|
||||
const img = new Image();
|
||||
|
||||
/** ********************* Add source to new image */
|
||||
img.src = blobURL;
|
||||
|
||||
imageDataBase64 = await new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
window.alert("Cannot load image!");
|
||||
};
|
||||
|
||||
/** ********************* Handle new image when loaded */
|
||||
img.onload = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
} else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
|
||||
if (imagePreviewNode) {
|
||||
document
|
||||
.querySelectorAll(`[data-imagepreview='image']`)
|
||||
.forEach((img) => {
|
||||
img.src = srcEncoded;
|
||||
});
|
||||
}
|
||||
|
||||
res(srcEncoded);
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
imageBase64: imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
};
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
|
||||
return {
|
||||
imageBase64: null,
|
||||
imageBase64Full: null,
|
||||
imageName: null,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
@@ -0,0 +1,104 @@
|
||||
type FunctionReturn = {
|
||||
imageBase64?: string;
|
||||
imageBase64Full?: string;
|
||||
imageName?: string;
|
||||
};
|
||||
|
||||
type Param = {
|
||||
imageInput: HTMLInputElement;
|
||||
maxWidth?: number;
|
||||
mimeType?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Image Input Element to Base 64
|
||||
*/
|
||||
export default async function imageInputToBase64({
|
||||
imageInput,
|
||||
maxWidth,
|
||||
mimeType,
|
||||
}: Param): Promise<FunctionReturn> {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imagePreviewNode = document.querySelector(
|
||||
`[data-imagepreview='image']`
|
||||
);
|
||||
let imageName = imageInput.files?.[0].name.replace(/\..*/, "");
|
||||
let imageDataBase64: string | undefined;
|
||||
|
||||
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
|
||||
const file = imageInput.files?.[0];
|
||||
const blobURL = file ? URL.createObjectURL(file) : undefined;
|
||||
const img = new Image();
|
||||
|
||||
if (blobURL) {
|
||||
img.src = blobURL;
|
||||
|
||||
imageDataBase64 = await new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
window.alert("Cannot load image!");
|
||||
};
|
||||
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target as HTMLImageElement;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
} else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
|
||||
if (imagePreviewNode) {
|
||||
document
|
||||
.querySelectorAll(`[data-imagepreview='image']`)
|
||||
.forEach((_img) => {
|
||||
const _imgEl = _img as HTMLImageElement;
|
||||
_imgEl.src = srcEncoded;
|
||||
});
|
||||
}
|
||||
|
||||
res(srcEncoded);
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
imageBase64: imageDataBase64?.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
};
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
} catch (/** @type {*} */ error: any) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
|
||||
return {};
|
||||
}
|
||||
}
|
||||
Vendored
-19
@@ -1,19 +0,0 @@
|
||||
declare namespace _exports {
|
||||
export { FunctionReturn };
|
||||
}
|
||||
declare function _exports({ inputFile, allowedRegex }: {
|
||||
inputFile: {
|
||||
name: string;
|
||||
size: number;
|
||||
type: string;
|
||||
};
|
||||
allowedRegex?: RegExp;
|
||||
}): Promise<FunctionReturn>;
|
||||
export = _exports;
|
||||
type FunctionReturn = {
|
||||
fileBase64: string;
|
||||
fileBase64Full: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
fileType: string;
|
||||
};
|
||||
@@ -1,96 +0,0 @@
|
||||
/**
|
||||
* @typedef {{
|
||||
* fileBase64: string,
|
||||
* fileBase64Full: string,
|
||||
* fileName: string,
|
||||
* fileSize: number,
|
||||
* fileType: string,
|
||||
* }} FunctionReturn
|
||||
*/
|
||||
|
||||
/**
|
||||
* Input File to base64
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description This function takes in a *SINGLE* input file from a HTML file input element.
|
||||
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
||||
* file from the array.
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single object passed
|
||||
* @param {object} params.inputFile - HTML input File
|
||||
* @param {string} params.inputFile.name - Input File Name
|
||||
* @param {number} params.inputFile.size - Input File Size in bytes
|
||||
* @param {string} params.inputFile.type - Input File Type: "JPEG", "PNG", "PDF", etc. Whichever allowed regexp is provided
|
||||
* @param {RegExp} [params.allowedRegex] - Regexp containing the allowed file types
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> } - Return Object
|
||||
*/
|
||||
module.exports = async function inputFileToBase64({ inputFile, allowedRegex }) {
|
||||
/**
|
||||
* == Initialize
|
||||
*
|
||||
* @description Initialize
|
||||
*/
|
||||
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
||||
|
||||
if (!inputFile?.type?.match(allowedTypesRegex)) {
|
||||
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
|
||||
|
||||
return {
|
||||
fileBase64: null,
|
||||
fileBase64Full: null,
|
||||
fileName: inputFile.name,
|
||||
fileSize: null,
|
||||
fileType: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
/** Process File **/
|
||||
let fileName = inputFile.name.replace(/\..*/, "");
|
||||
|
||||
/** Add source to new file **/
|
||||
const fileData = await new Promise((resolve, reject) => {
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(inputFile);
|
||||
reader.onload = function () {
|
||||
resolve(reader.result);
|
||||
};
|
||||
reader.onerror = function (/** @type {*} */ error) {
|
||||
console.log("Error: ", error.message);
|
||||
};
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return {
|
||||
fileBase64: fileData.replace(/.*?base64,/, ""),
|
||||
fileBase64Full: fileData,
|
||||
fileName: fileName,
|
||||
fileSize: inputFile.size,
|
||||
fileType: inputFile.type,
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("File Processing Error! =>", error.message);
|
||||
|
||||
return {
|
||||
fileBase64: null,
|
||||
fileBase64Full: null,
|
||||
fileName: inputFile.name,
|
||||
fileSize: null,
|
||||
fileType: null,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -0,0 +1,68 @@
|
||||
type FunctionReturn = {
|
||||
fileBase64?: string;
|
||||
fileBase64Full?: string;
|
||||
fileName?: string;
|
||||
fileSize?: number;
|
||||
fileType?: string;
|
||||
};
|
||||
|
||||
type Param = {
|
||||
inputFile: File;
|
||||
allowedRegex?: RegExp;
|
||||
};
|
||||
|
||||
/**
|
||||
* Input File to base64
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description This function takes in a *SINGLE* input file from a HTML file input element.
|
||||
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
||||
* file from the array.
|
||||
*/
|
||||
export default async function inputFileToBase64({
|
||||
inputFile,
|
||||
allowedRegex,
|
||||
}: Param): Promise<FunctionReturn> {
|
||||
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
||||
|
||||
if (!inputFile?.type?.match(allowedTypesRegex)) {
|
||||
window.alert(
|
||||
`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`
|
||||
);
|
||||
|
||||
return {
|
||||
fileName: inputFile.name,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
let fileName = inputFile.name.replace(/\..*/, "");
|
||||
|
||||
const fileData: string | undefined = await new Promise(
|
||||
(resolve, reject) => {
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(inputFile);
|
||||
reader.onload = function () {
|
||||
resolve(reader.result?.toString());
|
||||
};
|
||||
reader.onerror = function (/** @type {*} */ error: any) {
|
||||
console.log("Error: ", error.message);
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
fileBase64: fileData?.replace(/.*?base64,/, ""),
|
||||
fileBase64Full: fileData,
|
||||
fileName: fileName,
|
||||
fileSize: inputFile.size,
|
||||
fileType: inputFile.type,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.log("File Processing Error! =>", error.message);
|
||||
|
||||
return {
|
||||
fileName: inputFile.name,
|
||||
};
|
||||
}
|
||||
}
|
||||
Vendored
-2
@@ -1,2 +0,0 @@
|
||||
declare function _exports(): {} | null;
|
||||
export = _exports;
|
||||
@@ -1,65 +0,0 @@
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse request cookies
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description This function takes in a request object and returns the cookies as a JS object
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - main params object
|
||||
* @param {object} params.request - HTTPS request object
|
||||
*
|
||||
* @returns {{}|null}
|
||||
*/
|
||||
module.exports = function () {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** @type {string|null} */
|
||||
const cookieString = document.cookie;
|
||||
|
||||
if (!cookieString || typeof cookieString !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @type {string[]} */
|
||||
const cookieSplitArray = cookieString.split(";");
|
||||
|
||||
let cookieObject = {};
|
||||
|
||||
cookieSplitArray.forEach((keyValueString) => {
|
||||
const [key, value] = keyValueString.split("=");
|
||||
if (key && typeof key == "string") {
|
||||
cookieObject[key.replace(/^ +| +$/, "")] = value && typeof value == "string" ? value.replace(/^ +| +$/, "") : null;
|
||||
}
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
|
||||
return cookieObject;
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Parse request cookies
|
||||
* ============================================================================== *
|
||||
* @description This function takes in a request object and returns the cookies as a JS object
|
||||
*/
|
||||
export default function (): { [s: string]: any } | null {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
|
||||
const cookieString: string | null = document.cookie;
|
||||
|
||||
if (!cookieString || typeof cookieString !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cookieSplitArray: string[] = cookieString.split(";");
|
||||
|
||||
let cookieObject: { [s: string]: any } = {};
|
||||
|
||||
cookieSplitArray.forEach((keyValueString) => {
|
||||
const [key, value] = keyValueString.split("=");
|
||||
if (key && typeof key == "string") {
|
||||
cookieObject[key.replace(/^ +| +$/, "")] =
|
||||
value && typeof value == "string"
|
||||
? value.replace(/^ +| +$/, "")
|
||||
: null;
|
||||
}
|
||||
});
|
||||
|
||||
return cookieObject;
|
||||
}
|
||||
Reference in New Issue
Block a user