Skip to content

Commit

Permalink
chore: localize fetch-jsonp
Browse files Browse the repository at this point in the history
  • Loading branch information
ghiscoding committed Dec 13, 2024
1 parent 587abc1 commit 4d35685
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 9 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
"@slickgrid-universal/vanilla-force-bundle": "^5.10.2",
"bulma": "^1.0.2",
"dompurify": "^3.2.2",
"fetch-jsonp": "^1.3.0",
"moment-mini": "^2.29.4",
"rxjs": "^7.8.1",
"whatwg-fetch": "^3.6.20"
Expand Down
5 changes: 2 additions & 3 deletions src/examples/example04.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ import {
import { BindingEventService } from '@slickgrid-universal/binding';
import { ExcelExportService } from '@slickgrid-universal/excel-export';
import { Slicker, type SlickVanillaGridBundle } from '@slickgrid-universal/vanilla-bundle';
import fetchJsonp from 'fetch-jsonp';
// import { fetch } from 'whatwg-fetch';

import { ExampleGridOptions } from './example-grid-options';
import fetchJsonp from './jsonp';
import './example04.scss';

// const URL_COUNTRIES_COLLECTION = 'assets/data/countries.json';
Expand Down Expand Up @@ -252,7 +251,7 @@ export default class Example04 {
editorOptions: {
minLength: 3,
fetch: (searchText, updateCallback) => {
fetchJsonp(`http://gd.geobytes.com/AutoCompleteCity?q=${searchText}`)
fetchJsonp<string[]>(`http://gd.geobytes.com/AutoCompleteCity?q=${searchText}`, { crossorigin: true })
.then((response) => response.json())
.then((json) => updateCallback(json))
.catch((ex) => console.log('invalid JSONP response', ex));
Expand Down
92 changes: 92 additions & 0 deletions src/examples/jsonp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* copied and rewritten as ESM (just a simple rewrite as ESM to avoid loading a CJS package)
* https://github.com/camsong/fetch-jsonp/blob/master/src/fetch-jsonp.js
*/

interface JsonpOptions {
timeout: number;
jsonpCallback: string;
jsonpCallbackFunction: string;
charset: string;
nonce: string;
referrerPolicy: string;
crossorigin: boolean;
}

const defaultOptions = {
timeout: 5000,
jsonpCallback: 'callback',
jsonpCallbackFunction: null,
};
const generateCallbackFunction = () => `jsonp_${Date.now()}_${Math.ceil(Math.random() * 100000)}`;
const clearFunction = (functionName: string) => delete (window as any)[functionName];
const removeScript = (scriptId: string) => {
const script = document.getElementById(scriptId);
if (script) {
document.getElementsByTagName('head')[0].removeChild(script);
}
};

function fetchJsonp<T = any>(
_url: string,
options: Partial<JsonpOptions> = {}
): Promise<{ ok: boolean; json: () => Promise<T> }> {
// to avoid param reassign
let url = _url;
const timeout = options.timeout || defaultOptions.timeout;
const jsonpCallback = options.jsonpCallback || defaultOptions.jsonpCallback;
let timeoutId: any;

return new Promise((resolve, reject) => {
const callbackFunction = options.jsonpCallbackFunction || generateCallbackFunction();
const scriptId = `${jsonpCallback}_${callbackFunction}`;

(window as any)[callbackFunction] = (response: T) => {
// keep consistent with fetch API
resolve({ ok: true, json: () => Promise.resolve(response) });
if (timeoutId) clearTimeout(timeoutId);
removeScript(scriptId);
clearFunction(callbackFunction);
};

// Check if the user set their own params, and if not add a ? to start a list of params
url += url.indexOf('?') === -1 ? '?' : '&';

const jsonpScript = document.createElement('script');
jsonpScript.setAttribute('src', `${url}${jsonpCallback}=${callbackFunction}`);
if (options.charset) {
jsonpScript.setAttribute('charset', options.charset);
}
if (options.nonce) {
jsonpScript.setAttribute('nonce', options.nonce);
}
if (options.referrerPolicy) {
jsonpScript.setAttribute('referrerPolicy', options.referrerPolicy);
}
if (options.crossorigin) {
jsonpScript.setAttribute('crossorigin', 'true');
}
jsonpScript.id = scriptId;
document.getElementsByTagName('head')[0].appendChild(jsonpScript);

timeoutId = setTimeout(() => {
reject(new Error(`JSONP request to ${_url} timed out`));

clearFunction(callbackFunction);
removeScript(scriptId);
(window as any)[callbackFunction] = () => {
clearFunction(callbackFunction);
};
}, timeout);

// Caught if got 404/500
jsonpScript.onerror = () => {
reject(new Error(`JSONP request to ${_url} failed`));
clearFunction(callbackFunction);
removeScript(scriptId);
if (timeoutId) clearTimeout(timeoutId);
};
});
}

export default fetchJsonp;
5 changes: 0 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -705,11 +705,6 @@ fastq@^1.6.0:
dependencies:
reusify "^1.0.4"

fetch-jsonp@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/fetch-jsonp/-/fetch-jsonp-1.3.0.tgz#99b8c25bd100938d7a7a6b5db9d6b81f32a10809"
integrity sha512-hxCYGvmANEmpkHpeWY8Kawfa5Z1t2csTpIClIDG/0S92eALWHRU1RnGaj86Tf5Cc0QF+afSa4SQ4pFB2rFM5QA==

fflate@^0.8.2:
version "0.8.2"
resolved "https://registry.yarnpkg.com/fflate/-/fflate-0.8.2.tgz#fc8631f5347812ad6028bbe4a2308b2792aa1dea"
Expand Down

0 comments on commit 4d35685

Please sign in to comment.