Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { Component, enableProdMode, provideZoneChangeDetection } from '@angular/core';
import { HttpClient, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { HttpClient, provideHttpClient, withFetch } from '@angular/common/http';
import { lastValueFrom } from 'rxjs';
import * as AspNetData from 'devextreme-aspnet-data-nojquery';
import { DxDataGridComponent, DxDataGridModule, DxDataGridTypes } from 'devextreme-angular/ui/data-grid';
import { antiForgeryInterceptor, AntiForgeryTokenService } from './app.service';
import 'anti-forgery';

if (!/localhost/.test(document.location.host)) {
enableProdMode();
}

const BASE_PATH = 'https://js.devexpress.com/Demos/NetCore';
const URL = `${BASE_PATH}/api/DataGridBatchUpdateWebApi`;
const URL = 'https://js.devexpress.com/Demos/NetCore/api/DataGridBatchUpdateWebApi';

let modulePrefix = '';
// @ts-ignore
Expand All @@ -30,16 +29,12 @@ if (window && window.config?.packageConfigPaths) {
export class AppComponent {
ordersStore: AspNetData.CustomStore;

constructor(private http: HttpClient, private tokenService: AntiForgeryTokenService) {
constructor(private http: HttpClient) {
this.ordersStore = AspNetData.createStore({
key: 'OrderID',
loadUrl: `${URL}/Orders`,
async onBeforeSend(_method, ajaxOptions) {
const tokenData = await lastValueFrom(tokenService.getToken());
ajaxOptions.xhrFields = {
withCredentials: true,
headers: { [tokenData.headerName]: tokenData.token },
};
onBeforeSend(method, ajaxOptions) {
ajaxOptions.xhrFields = { withCredentials: true };
},
});
}
Expand All @@ -58,23 +53,16 @@ export class AppComponent {
changes: DxDataGridTypes.DataChange[],
component: DxDataGridComponent['instance'],
): Promise<void> {
try {
await lastValueFrom(
this.http.post(url, JSON.stringify(changes), {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
}),
);
await component.refresh(true);
component.cancelEditData();
} catch (error: any) {
const errorMessage = (typeof error?.error === 'string' && error.error)
? error.error
: (error?.statusText || 'Unknown error');
throw new Error(`Batch save failed: ${errorMessage}`);
}
await lastValueFrom(
this.http.post(url, JSON.stringify(changes), {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
}),
);
await component.refresh(true);
component.cancelEditData();
}

normalizeChanges(changes: DxDataGridTypes.DataChange[]): DxDataGridTypes.DataChange[] {
Expand Down Expand Up @@ -106,9 +94,6 @@ export class AppComponent {
bootstrapApplication(AppComponent, {
providers: [
provideZoneChangeDetection({ eventCoalescing: true, runCoalescing: true }),
provideHttpClient(
withFetch(),
withInterceptors([antiForgeryInterceptor]),
),
provideHttpClient(withFetch()),
],
});

This file was deleted.

82 changes: 17 additions & 65 deletions apps/demos/Demos/DataGrid/BatchUpdateRequest/React/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,55 +4,13 @@ import type { DataGridRef, DataGridTypes } from 'devextreme-react/data-grid';
import { createStore } from 'devextreme-aspnet-data-nojquery';
import 'whatwg-fetch';

const BASE_PATH = 'https://js.devexpress.com/Demos/NetCore';
const URL = `${BASE_PATH}/api/DataGridBatchUpdateWebApi`;

async function fetchAntiForgeryToken(): Promise<{ headerName: string; token: string }> {
try {
const response = await fetch(`${BASE_PATH}/api/Common/GetAntiForgeryToken`, {
method: 'GET',
credentials: 'include',
cache: 'no-cache',
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(`Failed to retrieve anti-forgery token: ${errorMessage || response.statusText}`);
}

return await response.json();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
throw new Error(errorMessage);
}
}

async function getAntiForgeryTokenValue(): Promise<{ headerName: string; token: string }> {
const tokenMeta = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]');
if (tokenMeta) {
const headerName = tokenMeta.dataset.headerName || 'RequestVerificationToken';
const token = tokenMeta.getAttribute('content') || '';
return Promise.resolve({ headerName, token });
}

const tokenData = await fetchAntiForgeryToken();
const meta = document.createElement('meta');
meta.name = 'csrf-token';
meta.content = tokenData.token;
meta.dataset.headerName = tokenData.headerName;
document.head.appendChild(meta);
return tokenData;
}
const URL = 'https://js.devexpress.com/Demos/NetCore/api/DataGridBatchUpdateWebApi';

const ordersStore = createStore({
key: 'OrderID',
loadUrl: `${URL}/Orders`,
async onBeforeSend(_method, ajaxOptions) {
const tokenData = await getAntiForgeryTokenValue();
ajaxOptions.xhrFields = {
withCredentials: true,
headers: { [tokenData.headerName]: tokenData.token },
};
onBeforeSend: (method, ajaxOptions) => {
ajaxOptions.xhrFields = { withCredentials: true };
},
});

Expand Down Expand Up @@ -81,31 +39,25 @@ function normalizeChanges(changes: DataGridTypes.DataChange[]): DataGridTypes.Da
}) as DataGridTypes.DataChange[];
}

async function sendBatchRequest(url: string, changes: DataGridTypes.DataChange[], headers: Record<string, string>) {
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(changes),
headers: {
'Content-Type': 'application/json;charset=UTF-8',
...headers,
},
credentials: 'include',
});
async function sendBatchRequest(url: string, changes: DataGridTypes.DataChange[]) {
const result = await fetch(url, {
method: 'POST',
body: JSON.stringify(changes),
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
credentials: 'include',
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(`Batch save failed: ${errorMessage || response.statusText}`);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
throw new Error(errorMessage);
if (!result.ok) {
const json = await result.json();

throw json.Message;
}
}

async function processBatchRequest(url: string, changes: DataGridTypes.DataChange[], component: ReturnType<DataGridRef['instance']>) {
const tokenData = await getAntiForgeryTokenValue();
await sendBatchRequest(url, changes, { [tokenData.headerName]: tokenData.token });
await sendBatchRequest(url, changes);
await component.refresh(true);
component.cancelEditData();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React from 'react';
import ReactDOM from 'react-dom';

import App from './App.tsx';
// eslint-disable-next-line import/no-unresolved
import 'anti-forgery';

ReactDOM.render(
<App />,
Expand Down
Loading
Loading