add header to fetch
This commit is contained in:
parent
ee299274a1
commit
4095d8d2b3
@ -1,21 +1,23 @@
|
|||||||
|
import { SsrDataFormatError } from "../others/errors";
|
||||||
|
import ssrConfig from "../ssr-config";
|
||||||
|
import { MINUTE } from "../utils/date";
|
||||||
|
import createNetworkCache from "./cache";
|
||||||
import {
|
import {
|
||||||
SsrHttpClientError,
|
SsrHttpClientError,
|
||||||
SsrHttpNotFoundError,
|
SsrHttpNotFoundError,
|
||||||
SsrHttpRateLimitError,
|
SsrHttpRateLimitError,
|
||||||
SsrHttpResponseError,
|
SsrHttpResponseError,
|
||||||
SsrHttpServerError, SsrHttpUnauthenticatedError,
|
SsrHttpServerError,
|
||||||
|
SsrHttpUnauthenticatedError,
|
||||||
SsrHttpUnauthorizedError,
|
SsrHttpUnauthorizedError,
|
||||||
SsrHttpUnprocessableEntityError,
|
SsrHttpUnprocessableEntityError,
|
||||||
SsrNetworkError,
|
SsrNetworkError,
|
||||||
} from './errors'
|
} from "./errors";
|
||||||
import {SsrDataFormatError} from '../others/errors'
|
import { parseRateLimitHeaders } from "./utils";
|
||||||
import {parseRateLimitHeaders} from './utils'
|
|
||||||
import {MINUTE} from '../utils/date'
|
|
||||||
import createNetworkCache from './cache';
|
|
||||||
|
|
||||||
const networkCache = createNetworkCache();
|
const networkCache = createNetworkCache();
|
||||||
|
|
||||||
const checkResponse = response => {
|
const checkResponse = (response) => {
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
// response.status >= 200 && response.status < 300
|
// response.status >= 200 && response.status < 300
|
||||||
return response;
|
return response;
|
||||||
@ -39,7 +41,7 @@ const checkResponse = response => {
|
|||||||
default:
|
default:
|
||||||
throw new SsrHttpResponseError(response);
|
throw new SsrHttpResponseError(response);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const getOptionsWithCacheKey = (url, options, cacheType = null) => {
|
const getOptionsWithCacheKey = (url, options, cacheType = null) => {
|
||||||
if (options && options.cacheKey) {
|
if (options && options.cacheKey) {
|
||||||
@ -48,7 +50,7 @@ const getOptionsWithCacheKey = (url, options, cacheType = null) => {
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options && options.method && options.method.toLowerCase() !== 'get') {
|
if (options && options.method && options.method.toLowerCase() !== "get") {
|
||||||
delete options.cacheKey;
|
delete options.cacheKey;
|
||||||
|
|
||||||
delete options.cacheTtl;
|
delete options.cacheTtl;
|
||||||
@ -56,68 +58,121 @@ const getOptionsWithCacheKey = (url, options, cacheType = null) => {
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
const newOptions = options ? {...options} : {};
|
const newOptions = options ? { ...options } : {};
|
||||||
|
|
||||||
if (!newOptions || !newOptions.hasOwnProperty('cacheTtl')) {
|
if (!newOptions || !newOptions.hasOwnProperty("cacheTtl")) {
|
||||||
newOptions.cacheTtl = MINUTE;
|
newOptions.cacheTtl = MINUTE;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {...newOptions, cacheKey: `${cacheType ? cacheType + ':' : ''}${url}`};
|
return {
|
||||||
}
|
...newOptions,
|
||||||
|
cacheKey: `${cacheType ? cacheType + ":" : ""}${url}`,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const setCacheIfNeeded = (response, cacheKey, cacheTtl) => {
|
const setCacheIfNeeded = (response, cacheKey, cacheTtl) => {
|
||||||
if (cacheKey && cacheTtl) networkCache.set(cacheKey, response, cacheTtl);
|
if (cacheKey && cacheTtl) networkCache.set(cacheKey, response, cacheTtl);
|
||||||
|
|
||||||
return {...response, cached: false};
|
return { ...response, cached: false };
|
||||||
}
|
};
|
||||||
|
|
||||||
export async function fetchUrl(url, options = {}, cors = true) {
|
export async function fetchUrl(url, options = {}, cors = true) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, {...options, ...(cors ? {mode: 'cors'} : null)});
|
console.log(ssrConfig.name);
|
||||||
|
const response = await fetch(url, {
|
||||||
|
...options,
|
||||||
|
headers: {
|
||||||
|
"x-requested-with": ssrConfig.name,
|
||||||
|
},
|
||||||
|
...(cors ? { mode: "cors" } : null),
|
||||||
|
});
|
||||||
|
|
||||||
return checkResponse(response);
|
return checkResponse(response);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof TypeError) throw new SsrNetworkError('Network error');
|
if (err instanceof TypeError) throw new SsrNetworkError("Network error");
|
||||||
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchJson(url, {cacheTtl = null, maxAge = null, ...restOptions} = {}) {
|
export async function fetchJson(
|
||||||
const options = getOptionsWithCacheKey(url, {cacheTtl, maxAge, ...restOptions}, 'json');
|
url,
|
||||||
|
{ cacheTtl = null, maxAge = null, ...restOptions } = {}
|
||||||
|
) {
|
||||||
|
const options = getOptionsWithCacheKey(
|
||||||
|
url,
|
||||||
|
{ cacheTtl, maxAge, ...restOptions },
|
||||||
|
"json"
|
||||||
|
);
|
||||||
|
|
||||||
const {cacheKey: fetchCacheKey, cacheTtl: fetchCacheTtl, maxAge: fetchMaxAge, ...fetchOptions} = getOptionsWithCacheKey(url, options, 'json');
|
const {
|
||||||
|
cacheKey: fetchCacheKey,
|
||||||
|
cacheTtl: fetchCacheTtl,
|
||||||
|
maxAge: fetchMaxAge,
|
||||||
|
...fetchOptions
|
||||||
|
} = getOptionsWithCacheKey(url, options, "json");
|
||||||
|
|
||||||
if (fetchCacheKey && fetchCacheTtl) {
|
if (fetchCacheKey && fetchCacheTtl) {
|
||||||
const cachedResponse = networkCache.get(fetchCacheKey, fetchMaxAge);
|
const cachedResponse = networkCache.get(fetchCacheKey, fetchMaxAge);
|
||||||
if (cachedResponse !== undefined) return {...cachedResponse, cached: true};
|
if (cachedResponse !== undefined)
|
||||||
|
return { ...cachedResponse, cached: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
return fetchUrl(url, fetchOptions)
|
return fetchUrl(url, fetchOptions)
|
||||||
.then(async response => {
|
.then(async (response) => {
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
|
|
||||||
return setCacheIfNeeded({headers: response.headers, rateLimit: parseRateLimitHeaders(response), body}, fetchCacheKey, fetchCacheTtl);
|
return setCacheIfNeeded(
|
||||||
})
|
{
|
||||||
.catch(err => {
|
headers: response.headers,
|
||||||
throw (err instanceof SyntaxError ? new SsrDataFormatError('JSON parse error', err) : err);
|
rateLimit: parseRateLimitHeaders(response),
|
||||||
|
body,
|
||||||
|
},
|
||||||
|
fetchCacheKey,
|
||||||
|
fetchCacheTtl
|
||||||
|
);
|
||||||
})
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
throw err instanceof SyntaxError
|
||||||
|
? new SsrDataFormatError("JSON parse error", err)
|
||||||
|
: err;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchHtml(url, {cacheTtl = null, maxAge = null, ...restOptions} = {}) {
|
export async function fetchHtml(
|
||||||
const options = getOptionsWithCacheKey(url, {cacheTtl, maxAge, ...restOptions}, 'json');
|
url,
|
||||||
|
{ cacheTtl = null, maxAge = null, ...restOptions } = {}
|
||||||
|
) {
|
||||||
|
const options = getOptionsWithCacheKey(
|
||||||
|
url,
|
||||||
|
{ cacheTtl, maxAge, ...restOptions },
|
||||||
|
"json"
|
||||||
|
);
|
||||||
|
|
||||||
const {cacheKey: fetchCacheKey, cacheTtl: fetchCacheTtl, maxAge: fetchMaxAge, ...fetchOptions} = getOptionsWithCacheKey(url, options, 'html');
|
const {
|
||||||
|
cacheKey: fetchCacheKey,
|
||||||
|
cacheTtl: fetchCacheTtl,
|
||||||
|
maxAge: fetchMaxAge,
|
||||||
|
...fetchOptions
|
||||||
|
} = getOptionsWithCacheKey(url, options, "html");
|
||||||
|
|
||||||
if (fetchCacheKey && fetchCacheTtl) {
|
if (fetchCacheKey && fetchCacheTtl) {
|
||||||
const cachedResponse = networkCache.get(fetchCacheKey, fetchMaxAge);
|
const cachedResponse = networkCache.get(fetchCacheKey, fetchMaxAge);
|
||||||
if (cachedResponse !== undefined) return {...cachedResponse, cached: true};
|
if (cachedResponse !== undefined)
|
||||||
|
return { ...cachedResponse, cached: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
return fetchUrl(url, fetchOptions)
|
return fetchUrl(url, fetchOptions).then(async (response) => {
|
||||||
.then(async response => {
|
const body = await response.text();
|
||||||
const body = await response.text();
|
|
||||||
|
|
||||||
return setCacheIfNeeded({headers: response.headers, rateLimit: parseRateLimitHeaders(response), body: new DOMParser().parseFromString(body, 'text/html')}, fetchCacheKey, fetchCacheTtl);
|
return setCacheIfNeeded(
|
||||||
})
|
{
|
||||||
}
|
headers: response.headers,
|
||||||
|
rateLimit: parseRateLimitHeaders(response),
|
||||||
|
body: new DOMParser().parseFromString(body, "text/html"),
|
||||||
|
},
|
||||||
|
fetchCacheKey,
|
||||||
|
fetchCacheTtl
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user