mirror of https://github.com/sveltejs/svelte
parent
ef11dae8ce
commit
d36894a5c0
@ -1,44 +1,17 @@
|
||||
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
|
||||
/** @import { GetRequestInit, Resource } from '#shared' */
|
||||
import { cache } from './cache';
|
||||
import { fetch_json } from '../../shared/utils.js';
|
||||
import { hydratable } from '../context';
|
||||
import { resource } from './resource';
|
||||
|
||||
/**
|
||||
* @template {StandardSchemaV1} TSchema
|
||||
* @param {{ schema?: TSchema, url: string | URL, init?: RequestInit }} args
|
||||
* @param {string} [key]
|
||||
* @template TReturn
|
||||
* @param {string | URL} url
|
||||
* @param {GetRequestInit} [init]
|
||||
* @returns {Resource<TReturn>}
|
||||
*/
|
||||
async function fetcher_impl({ schema, url, init }, key) {
|
||||
const response = await fetch(url, init);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Fetch error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
if (schema) {
|
||||
const data = await response.json();
|
||||
return schema['~standard'].validate(data);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const cached_fetch = cache('svelte/fetcher', fetcher_impl, {
|
||||
hash: (arg) => {
|
||||
return `${typeof arg.url === 'string' ? arg.url : arg.url.toString()}}`;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @template {StandardSchemaV1} TSchema
|
||||
* @overload
|
||||
* @param {{ schema: TSchema, url: string | URL, init?: RequestInit }} arg
|
||||
* @returns {Promise<StandardSchemaV1.InferOutput<TSchema>>}
|
||||
*/
|
||||
/**
|
||||
* @overload
|
||||
* @param {{ schema?: undefined, url: string | URL, init?: RequestInit }} arg
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
/**
|
||||
* @template {StandardSchemaV1} TSchema
|
||||
* @param {{ schema?: TSchema, url: string | URL, init?: RequestInit }} arg
|
||||
*/
|
||||
export function fetcher(arg) {
|
||||
return cached_fetch(arg);
|
||||
export function fetcher(url, init) {
|
||||
return cache(`svelte/fetcher::::${typeof url === 'string' ? url : url.toString()}`, () =>
|
||||
resource(() => hydratable(() => fetch_json(url, init)))
|
||||
);
|
||||
}
|
||||
|
||||
@ -0,0 +1,17 @@
|
||||
/** @import { GetRequestInit, Resource } from '#shared' */
|
||||
import { fetch_json } from '../../shared/utils.js';
|
||||
import { hydratable } from '../context.js';
|
||||
import { cache } from './cache';
|
||||
import { resource } from './resource.js';
|
||||
|
||||
/**
|
||||
* @template TReturn
|
||||
* @param {string | URL} url
|
||||
* @param {GetRequestInit} [init]
|
||||
* @returns {Resource<TReturn>}
|
||||
*/
|
||||
export function fetcher(url, init) {
|
||||
return cache(`svelte/fetcher::::${typeof url === 'string' ? url : url.toString()}`, () =>
|
||||
resource(() => hydratable(() => fetch_json(url, init)))
|
||||
);
|
||||
}
|
||||
Loading…
Reference in new issue