From 7d38d64c478c8c62c8cff12f3c1ee72729a7b80d Mon Sep 17 00:00:00 2001 From: StefanVukovic99 Date: Sun, 4 Feb 2024 08:08:06 +0100 Subject: Extract fetch functions to utilities (#629) * do backend * other files * move fetch utils to own file * remove extra line * add extra line * remove unnecessary export * undo changes to cssStyleApplier --- ext/js/background/backend.js | 48 ++++------------------------------- ext/js/core/fetch-utilities.js | 57 ++++++++++++++++++++++++++++++++++++++++++ ext/js/data/options-util.js | 46 +++------------------------------- 3 files changed, 66 insertions(+), 85 deletions(-) create mode 100644 ext/js/core/fetch-utilities.js diff --git a/ext/js/background/backend.js b/ext/js/background/backend.js index b95626f5..af0b3039 100644 --- a/ext/js/background/backend.js +++ b/ext/js/background/backend.js @@ -23,7 +23,7 @@ import {ClipboardReader} from '../comm/clipboard-reader.js'; import {Mecab} from '../comm/mecab.js'; import {createApiMap, invokeApiMapHandler} from '../core/api-map.js'; import {ExtensionError} from '../core/extension-error.js'; -import {readResponseJson} from '../core/json.js'; +import {fetchJson, fetchText} from '../core/fetch-utilities.js'; import {log} from '../core/logger.js'; import {clone, deferPromise, isObject, promiseTimeout} from '../core/utilities.js'; import {isNoteDataValid} from '../data/anki-util.js'; @@ -279,11 +279,11 @@ export class Backend { } /** @type {import('language-transformer').LanguageTransformDescriptor} */ - const descriptor = await this._fetchJson('/data/language/japanese-transforms.json'); + const descriptor = await fetchJson('/data/language/japanese-transforms.json'); this._translator.prepare(descriptor); await this._optionsUtil.prepare(); - this._defaultAnkiFieldTemplates = (await this._fetchText('/data/templates/default-anki-field-templates.handlebars')).trim(); + this._defaultAnkiFieldTemplates = (await fetchText('/data/templates/default-anki-field-templates.handlebars')).trim(); this._options = await this._optionsUtil.load(); this._applyOptions('background'); @@ -668,7 +668,7 @@ export class Backend { if (!url.startsWith('/') || url.startsWith('//') || !url.endsWith('.css')) { throw new Error('Invalid URL'); } - return await this._fetchText(url); + return await fetchText(url); } /** @type {import('api').ApiHandler<'getEnvironmentInfo'>} */ @@ -683,7 +683,7 @@ export class Backend { /** @type {import('api').ApiHandler<'getDisplayTemplatesHtml'>} */ async _onApiGetDisplayTemplatesHtml() { - return await this._fetchText('/display-templates.html'); + return await fetchText('/display-templates.html'); } /** @type {import('api').ApiHandler<'getZoom'>} */ @@ -1848,44 +1848,6 @@ export class Backend { }); } - /** - * @param {string} url - * @returns {Promise} - */ - async _fetchAsset(url) { - const response = await fetch(chrome.runtime.getURL(url), { - method: 'GET', - mode: 'no-cors', - cache: 'default', - credentials: 'omit', - redirect: 'follow', - referrerPolicy: 'no-referrer' - }); - if (!response.ok) { - throw new Error(`Failed to fetch ${url}: ${response.status}`); - } - return response; - } - - /** - * @param {string} url - * @returns {Promise} - */ - async _fetchText(url) { - const response = await this._fetchAsset(url); - return await response.text(); - } - - /** - * @template [T=unknown] - * @param {string} url - * @returns {Promise} - */ - async _fetchJson(url) { - const response = await this._fetchAsset(url); - return await readResponseJson(response); - } - /** * @template {import('application').ApiNames} TName * @param {import('application').ApiMessage} message diff --git a/ext/js/core/fetch-utilities.js b/ext/js/core/fetch-utilities.js new file mode 100644 index 00000000..074f7c9a --- /dev/null +++ b/ext/js/core/fetch-utilities.js @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2024 Yomitan Authors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import {readResponseJson} from './json.js'; + +/** + * @param {string} url + * @returns {Promise} + */ +async function fetchAsset(url) { + const response = await fetch(chrome.runtime.getURL(url), { + method: 'GET', + mode: 'no-cors', + cache: 'default', + credentials: 'omit', + redirect: 'follow', + referrerPolicy: 'no-referrer' + }); + if (!response.ok) { + throw new Error(`Failed to fetch ${url}: ${response.status}`); + } + return response; +} + + +/** + * @param {string} url + * @returns {Promise} + */ +export async function fetchText(url) { + const response = await fetchAsset(url); + return await response.text(); +} + +/** + * @template [T=unknown] + * @param {string} url + * @returns {Promise} + */ +export async function fetchJson(url) { + const response = await fetchAsset(url); + return await readResponseJson(response); +} \ No newline at end of file diff --git a/ext/js/data/options-util.js b/ext/js/data/options-util.js index cbaeb92b..3f3a5ab8 100644 --- a/ext/js/data/options-util.js +++ b/ext/js/data/options-util.js @@ -16,8 +16,9 @@ * along with this program. If not, see . */ +import {fetchJson, fetchText} from '../core/fetch-utilities.js'; +import {parseJson} from '../core/json.js'; import {escapeRegExp, isObject} from '../core/utilities.js'; -import {parseJson, readResponseJson} from '../core/json.js'; import {TemplatePatcher} from '../templates/template-patcher.js'; import {JsonSchema} from './json-schema.js'; @@ -32,7 +33,7 @@ export class OptionsUtil { /** */ async prepare() { /** @type {import('ext/json-schema').Schema} */ - const schema = await this._fetchJson('/data/schemas/options-schema.json'); + const schema = await fetchJson('/data/schemas/options-schema.json'); this._optionsSchema = new JsonSchema(schema); } @@ -438,7 +439,7 @@ export class OptionsUtil { if (fieldTemplates === null) { continue; } if (patch === null) { - const content = await this._fetchText(modificationsUrl); + const content = await fetchText(modificationsUrl); if (this._templatePatcher === null) { this._templatePatcher = new TemplatePatcher(); } @@ -449,45 +450,6 @@ export class OptionsUtil { } } - /** - * @param {string} url - * @returns {Promise} - */ - async _fetchGeneric(url) { - url = chrome.runtime.getURL(url); - const response = await fetch(url, { - method: 'GET', - mode: 'no-cors', - cache: 'default', - credentials: 'omit', - redirect: 'follow', - referrerPolicy: 'no-referrer' - }); - if (!response.ok) { - throw new Error(`Failed to fetch ${url}: ${response.status}`); - } - return response; - } - - /** - * @param {string} url - * @returns {Promise} - */ - async _fetchText(url) { - const response = await this._fetchGeneric(url); - return await response.text(); - } - - /** - * @template [T=unknown] - * @param {string} url - * @returns {Promise} - */ - async _fetchJson(url) { - const response = await this._fetchGeneric(url); - return await readResponseJson(response); - } - /** * @param {string} string * @returns {number} -- cgit v1.2.3