Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added extensibility point to provide custom fetch implementation #1339

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/Framework/Framework/Resources/Scripts/dotvvm-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ type DotvvmCoreState = {
_viewModelCacheId?: string
_virtualDirectory: string
_initialUrl: string,
_routeName: string,
_routeParameters: {
[name: string]: any
},
_stateManager: StateManager<RootViewModel>
}

Expand Down Expand Up @@ -60,7 +64,8 @@ export function clearViewModelCache() {
delete getCoreState()._viewModelCache;
}
export function getCulture(): string { return getCoreState()._culture; }

export function getRouteName(): string { return getCoreState()._routeName; }
export function getRouteParameters(): { [name: string]: any } { return getCoreState()._routeParameters; }
export function getStateManager(): StateManager<RootViewModel> { return getCoreState()._stateManager }

let initialViewModelWrapper: any;
Expand All @@ -85,7 +90,9 @@ export function initCore(culture: string): void {
_culture: culture,
_initialUrl: thisViewModel.url,
_virtualDirectory: thisViewModel.virtualDirectory!,
_stateManager: manager
_stateManager: manager,
_routeName: thisViewModel.routeName,
_routeParameters: thisViewModel.routeParameters
}

// store cached viewmodel
Expand All @@ -106,7 +113,9 @@ export function initCore(culture: string): void {
_culture: currentCoreState!._culture,
_initialUrl: a.serverResponseObject.url,
_virtualDirectory: a.serverResponseObject.virtualDirectory!,
_stateManager: currentCoreState!._stateManager
_stateManager: currentCoreState!._stateManager,
_routeName: a.serverResponseObject.routeName,
_routeParameters: a.serverResponseObject.routeParameters
}
});
}
Expand All @@ -125,3 +134,11 @@ function persistViewModel() {

getViewModelStorageElement().value = JSON.stringify(persistedViewModel);
}

let _customFetch: (url: string, init: RequestInit) => Promise<Response> = fetch;
export function customFetch(url: string, init: RequestInit): Promise<Response> {
return _customFetch(url, init);
}
export function setCustomFetch(fetchImplementation: (url: string, init: RequestInit) => Promise<Response>) {
_customFetch = fetchImplementation;
}
7 changes: 6 additions & 1 deletion src/Framework/Framework/Resources/Scripts/dotvvm-root.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { initCore, getViewModel, getViewModelObservable, initBindings, getCulture, getState, getStateManager } from "./dotvvm-base"
import { initCore, getViewModel, getViewModelObservable, initBindings, getCulture, getState, getStateManager, getRouteName, getRouteParameters, setCustomFetch, customFetch } from "./dotvvm-base"
import * as events from './events'
import * as spa from "./spa/spa"
import * as validation from './validation/validation'
Expand Down Expand Up @@ -86,6 +86,8 @@ const dotvvmExports = {
get viewModel() { return getViewModel() }
}
},
get routeName() { return getRouteName() },
get routeParameters() { return getRouteParameters() },
get state() { return getState() },
patchState(a: any) {
getStateManager().patchState(a)
Expand All @@ -109,6 +111,7 @@ const dotvvmExports = {
registerOne: viewModuleManager.registerViewModule,
init: viewModuleManager.initViewModule,
call: viewModuleManager.callViewModuleCommand,
callNamedCommand: viewModuleManager.callNamedCommand,
registerMany: viewModuleManager.registerViewModules
},
resourceLoader: {
Expand All @@ -130,6 +133,8 @@ const dotvvmExports = {
} as any,
StateManager,
DotvvmEvent,
get customFetch(): (url: string, init: RequestInit) => Promise<Response> { return customFetch },
set customFetch(implementation: (url: string, init: RequestInit) => Promise<Response>) { setCustomFetch(implementation); }
}

if (compileConstants.isSpa) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -321,4 +321,4 @@ type DotvvmViewModule = {
$dispose?: (context: any) => void

[commandName: DotvvmViewModuleCommandName]: (...args: any[]) => Promise<any> | any
}
}
6 changes: 3 additions & 3 deletions src/Framework/Framework/Resources/Scripts/postback/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getVirtualDirectory, getViewModel, getState, getStateManager } from '../dotvvm-base';
import { getVirtualDirectory, getViewModel, getState, getStateManager, customFetch } from '../dotvvm-base';
import { DotvvmPostbackError } from '../shared-classes';
import { logInfoVerbose, logWarning } from '../utils/logging';
import { keys } from '../utils/objects';
Expand Down Expand Up @@ -32,7 +32,7 @@ export async function postJSON<T>(url: string, postData: any, signal: AbortSigna
export async function fetchJson<T>(url: string, init: RequestInit): Promise<WrappedResponse<T>> {
let response: Response;
try {
response = await fetch(url, init);
response = await customFetch(url, init);
}
catch (err) {
throw new DotvvmPostbackError({ type: "network", err });
Expand All @@ -55,7 +55,7 @@ export async function fetchCsrfToken(signal: AbortSignal | undefined): Promise<s
let response;
try {
const url = addLeadingSlash(concatUrl(getVirtualDirectory() || "", "___dotvvm-create-csrf-token___"));
response = await fetch(url, { signal });
response = await customFetch(url, { signal });
}
catch (err) {
logWarning("postback", `CSRF token fetch failed.`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,38 @@ export function callViewModuleCommand(viewIdOrElement: string | HTMLElement, com
}
}

export function callNamedCommand(viewIdOrElement: string | HTMLElement, commandName: string, args: any[], allowAsync: boolean = true) {
if (compileConstants.debug && commandName == null) { throw new Error("commandName has to have a value"); }
if (compileConstants.debug && !(args instanceof Array)) { throw new Error("args must be an array"); }

const foundModules: ModuleContext[] = [];

for (let context of getModules(viewIdOrElement)) {
if (commandName in context.namedCommands && typeof context.namedCommands[commandName] === "function") {
foundModules.push(context);
}
}

if (compileConstants.debug && !foundModules.length) {
throw new Error(`Named command ${commandName} could not be found in view ${viewIdOrElement}.`);
}

if (compileConstants.debug && foundModules.length > 1) {
throw new Error(`Conflict: There were multiple named commands ${commandName} in view ${viewIdOrElement}.`);
}

try {
var result = foundModules[0].namedCommands[commandName](...args.map(v => serialize(v)));
if (!allowAsync && result instanceof Promise) {
throw compileConstants.debug ? `Named command returned Promise even though it was called through _js.Invoke("${commandName}", ...). Use the _js.InvokeAsync method to call commands which (may) return a promise.` : "Command returned Promise";
}
return result
}
catch (e: unknown) {
throw new Error(`While executing command ${commandName}(${args.map(v => JSON.stringify(serialize(v)))}), an error occurred. ${e}`);
}
}

const globalComponent: { [key: string]: DotvvmJsComponentFactory } = {}

export function findComponent(
Expand Down Expand Up @@ -244,7 +276,7 @@ function mapCommandResult(result: any) {
}

export class ModuleContext {
private readonly namedCommands: { [name: string]: (...args: any[]) => Promise<any> } = {};
readonly namedCommands: { [name: string]: (...args: any[]) => Promise<any> } = {};
public module: any;

constructor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ public void BuildViewModel(IDotvvmRequestContext context, object? commandResult)
result["renderedResources"] = JArray.FromObject(context.ResourceManager.GetNamedResourcesInOrder().Select(r => r.Name));
}

if (context.Route != null)
{
result["routeName"] = context.Route.RouteName;
result["routeParameters"] = new JObject(context.Parameters.Select(p => new JProperty(p.Key, p.Value)).ToArray());
}

// TODO: do not send on postbacks
if (validationRules?.Count > 0) result["validationRules"] = validationRules;

Expand Down