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

Remove Axios #2006

Open
wants to merge 23 commits into
base: dev
Choose a base branch
from
Open
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
11 changes: 11 additions & 0 deletions CHANGELOG.md
addy-pathania marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ Our versioning strategy is as follows:
* `[sitecore-jss-nextjs]` Fixed handling of ? inside square brackets [] in regex patterns to prevent incorrect escaping ([#1999](https://github.com/Sitecore/jss/pull/1999))
* `[sitecore-jss-nextjs]` Improve performance for redirect middleware ([#2003](https://github.com/Sitecore/jss/pull/2003))

### 🛠 Breaking Change

* `[all packages]` `[all samples]` Remove Axios ([#2006](https://github.com/Sitecore/jss/pull/2006))
* `AxiosDataFetcher` is replaced by the `NativeDataFetcher`.
* `AxiosDataFetcherConfig` is replaced by `NativeDataFetcherConfig`.
* `AxiosResponse` is replaced by `NativeDataFetcherResponse`.
* `NativeDataFetcherError`: a new error type introduced for native data fetching operations.
* Default `NativeDataFetcher` is of type `NativeDataFetcherFunction<T>` but can be overridden by custom fetcher using the existing `HttpDataFetcher<T>` type.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this about data-fetcher.ts file? Can you rephrase this paragraph please, for clarity?

* `NativeDataFetcher` now exposes `fetch`, `get`, `post`, `delete`, `put`, `head` methods.
* `NativedDataFetcher.fetch` now accepts second parameter of type `RequestInit` instead of `unknown`.

## 22.3.0 / 22.3.1

### 🐛 Bug Fixes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,18 @@ import { HttpResponse } from '@sitecore-jss/sitecore-jss-angular';
import { Observable, lastValueFrom } from 'rxjs';

@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class JssDataFetcherService {
constructor(
private readonly httpClient: HttpClient,
) {
constructor(private readonly httpClient: HttpClient) {
this.fetch = this.fetch.bind(this);
}

fetch<T>(url: string, data: unknown): Promise<HttpResponse<T>> {
let result: Observable<T>;

const options = {
withCredentials: true,
credentials: 'include',
};

if (data) {
Expand All @@ -28,9 +26,9 @@ export class JssDataFetcherService {

return lastValueFrom(result)
.then((responseData) => ({
data: responseData as T,
status: 200,
statusText: 'OK'
data: responseData as T,
status: 200,
statusText: 'OK',
}))
.catch((error: HttpErrorResponse) => {
if (error instanceof Error) {
Expand All @@ -40,7 +38,7 @@ export class JssDataFetcherService {
return {
data: error.error as T,
status: error.status,
statusText: error.statusText
statusText: error.statusText,
};
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { AxiosDataFetcher, AxiosResponse } from '@sitecore-jss/sitecore-jss-nextjs';
import { NativeDataFetcher, NativeDataFetcherResponse } from '@sitecore-jss/sitecore-jss-nextjs';

/**
* Implements a data fetcher using Axios - replace with your favorite
* Implements a data fetcher using NativeDataFetcher - replace with your favorite
* SSR-capable HTTP or fetch library if you like. See HttpDataFetcher<T> type
* in sitecore-jss library for implementation details/notes.
* @param {string} url The URL to request; may include query string
* @param {unknown} data Optional data to POST with the request.
* @param {RequestInit} data Optional data to POST with the request.
*/
export function dataFetcher<ResponseType>(
url: string,
data?: unknown
): Promise<AxiosResponse<ResponseType>> {
return new AxiosDataFetcher().fetch<ResponseType>(url, data);
data?: RequestInit
): Promise<NativeDataFetcherResponse<ResponseType>> {
return new NativeDataFetcher().fetch<ResponseType>(url, data);
addy-pathania marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { AxiosDataFetcher, GraphQLSitemapXmlService, AxiosResponse } from '@sitecore-jss/sitecore-jss-nextjs';
import { NativeDataFetcher, GraphQLSitemapXmlService } from '@sitecore-jss/sitecore-jss-nextjs'
import { siteResolver } from 'lib/site-resolver';
import config from 'temp/config';
import clientFactory from 'lib/graphql-client-factory';
Expand Down Expand Up @@ -33,28 +33,39 @@ const sitemapApi = async (
const sitemapUrl = isAbsoluteUrl ? sitemapPath : `${config.sitecoreApiHost}${sitemapPath}`;
res.setHeader('Content-Type', 'text/xml;charset=utf-8');

// need to prepare stream from sitemap url
return new AxiosDataFetcher()
.get(sitemapUrl, {
responseType: 'stream',
addy-pathania marked this conversation as resolved.
Show resolved Hide resolved
})
.then((response: AxiosResponse) => {
response.data.pipe(res);
})
.catch(() => res.redirect('/404'));
try {
const fetcher = new NativeDataFetcher();
const response = await fetcher.fetch(sitemapUrl);

const reader = response.data?.getReader();
if (reader) {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) res.write(value);
}
}
res.end();
} catch (error) {
return res.redirect('/404');
}
return;
}




// this approache if user go to /sitemap.xml - under it generate xml page with list of sitemaps
const sitemaps = await sitemapXmlService.fetchSitemaps();

if (!sitemaps.length) {
return res.redirect('/404');
}

const reqtHost = req.headers.host;
const reqProtocol = req.headers['x-forwarded-proto'] || 'https';
const SitemapLinks = sitemaps
.map((item) => {
.map((item: string) => {
const parseUrl = item.split('/');
const lastSegment = parseUrl[parseUrl.length - 1];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
"dependencies": {
"@apollo/client": "^3.7.1",
"@sitecore-jss/sitecore-jss-react": "~<%- version %>",
"axios": "^1.2.0",
"bootstrap": "^5.2.3",
"cross-fetch": "^3.1.5",
"fast-deep-equal": "^3.1.3",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import React from 'react';
import { StaticRouter } from 'react-router-dom/server';
import { renderToStringWithData } from '@apollo/client/react/ssr';
import Helmet from 'react-helmet';
import axios from 'axios';
import http from 'http';
import https from 'https';
import GraphQLClientFactory from '../src/lib/GraphQLClientFactory';
Expand Down Expand Up @@ -31,9 +30,6 @@ function assertReplace(string, value, replacement) {

// Setup Http/Https agents for keep-alive. Used in headless-proxy
export const setUpDefaultAgents = (httpAgent, httpsAgent) => {
axios.defaults.httpAgent = httpAgent;
axios.defaults.httpsAgent = httpsAgent;

http.globalAgent = httpAgent;
https.globalAgent = httpsAgent;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import axios from 'axios';
import { NativeDataFetcher } from '@sitecore-jss/sitecore-jss';

/**
* Implements a data fetcher using Axios - replace with your favorite
* Implements a data fetcher using NativeDataFetcher - replace with your favorite
* SSR-capable HTTP or fetch library if you like. See HttpDataFetcher<T> type
* in sitecore-jss library for implementation details/notes.
* @param {string} url The URL to request; may include query string
* @param {any} data Optional data to POST with the request.
*/
export function dataFetcher(url, data) {
return axios({
url,
export async function dataFetcher(url, data) {
const fetcher = new NativeDataFetcher({ credentials: 'include' });

const response = await fetcher.fetch(url, {
method: data ? 'POST' : 'GET',
data,
// note: axios needs to use `withCredentials: true` in order for Sitecore cookies to be included in CORS requests
// which is necessary for analytics and such
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
body: data ? JSON.stringify(data) : undefined,
});

return response.data;
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
"@vue/apollo-composable": "4.0.0-beta.2",
"@vue/apollo-option": "^4.0.0",
"@vue/apollo-ssr": "^4.0.0",
"axios": "^1.2.3",
"bootstrap": "^5.2.3",
"cross-fetch": "~3.1.5",
"graphql": "^16.6.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { renderToString } from '@vue/server-renderer';
import serializeJavascript from 'serialize-javascript';
import { renderMetaToString } from 'vue-meta/ssr';
import axios from 'axios';
import http from 'http';
import https from 'https';
import i18ninit from '../src/i18n';
Expand Down Expand Up @@ -29,9 +28,6 @@ function assertReplace(string, value, replacement) {

// Setup Http/Https agents for keep-alive. Used in headless-proxy
export const setUpDefaultAgents = (httpAgent, httpsAgent) => {
axios.defaults.httpAgent = httpAgent;
axios.defaults.httpsAgent = httpsAgent;

http.globalAgent = httpAgent;
https.globalAgent = httpsAgent;
};
Expand Down
24 changes: 13 additions & 11 deletions packages/create-sitecore-jss/src/templates/vue/src/dataFetcher.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import axios from 'axios';
import { NativeDataFetcher } from '@sitecore-jss/sitecore-jss';

/**
* Implements a data fetcher using Axios - replace with your favorite
* SSR-capable HTTP or fetch library if you like. See HttpDataFetcher<T> type
* in sitecore-jss library for implementation details/notes.
* Implements a data fetcher using NativeDataFetcher - replace with your favorite
* SSR-capable HTTP or fetch library if you like.
* @param {string} url The URL to request; may include query string
* @param {any} data Optional data to POST with the request.
*/
export function dataFetcher(url, data) {
return axios({
url,
export async function dataFetcher(url, data) {
const fetcher = new NativeDataFetcher({ credentials: 'include' });

const response = await fetcher.fetch(url, {
method: data ? 'POST' : 'GET',
data,
// note: axios needs to use `withCredentials: true` in order for Sitecore cookies to be included in CORS requests
// which is necessary for analytics and such
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
body: data ? JSON.stringify(data) : undefined,
});

return response.data;
}
4 changes: 4 additions & 0 deletions packages/sitecore-jss-angular/src/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ export {
export {
constants,
HttpDataFetcher,
NativeDataFetcher,
NativeDataFetcherConfig,
NativeDataFetcherResponse,
NativeDataFetcherError,
HttpResponse,
enableDebug,
ClientError,
Expand Down
2 changes: 1 addition & 1 deletion packages/sitecore-jss-dev-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"dependencies": {
"@babel/parser": "^7.24.0",
"@sitecore-jss/sitecore-jss": "22.4.0-canary.9",
"axios": "^1.3.2",
"chalk": "^4.1.2",
"chokidar": "^3.6.0",
"del": "^6.0.0",
Expand All @@ -51,6 +50,7 @@
"recast": "^0.23.5",
"resolve": "^1.22.1",
"ts-node": "^10.9.1",
"undici": "^7.2.1",
"url-join": "^4.0.1",
"uuid": "^9.0.0",
"yargs": "^17.6.2"
Expand Down
Loading