Skip to content

Commit

Permalink
Merge pull request #490 from alovajs/fix/ssr
Browse files Browse the repository at this point in the history
fix: ssr in codesandbox
  • Loading branch information
JOU-amjs authored Aug 3, 2024
2 parents bdf9f14 + 5b381b4 commit 5c5b7db
Show file tree
Hide file tree
Showing 11 changed files with 70 additions and 24 deletions.
6 changes: 6 additions & 0 deletions .changeset/polite-cheetahs-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@alova/shared': patch
'alova': patch
---

fix: ssr in codesandbox
5 changes: 5 additions & 0 deletions .changeset/spicy-moose-pull.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'alova': patch
---

use the newest params to request modified in `beforeRequest`
5 changes: 3 additions & 2 deletions packages/alova/src/defaults/cacheLogger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { STORAGE_RESTORE, isSSR, len } from '@alova/shared/vars';
import { globalConfigMap } from '@/globalConfig';
import { STORAGE_RESTORE, len } from '@alova/shared/vars';
import { CacheMode } from '~/typings';
import { Method } from '..';

Expand All @@ -16,7 +17,7 @@ export default (response: any, methodInstance: Method, cacheMode: CacheMode, tag
const labelStyle = '\x1B[32m%s\x1B[39m';
const startSep = ` [HitCache]${url} `;
const endSepFn = () => Array(len(startSep) + 1).join('^');
if (isSSR) {
if (globalConfigMap.ssr) {
log(hdStyle, startSep);
log(labelStyle, ' Cache ', response);
log(labelStyle, ' Mode ', cacheMode);
Expand Down
4 changes: 3 additions & 1 deletion packages/alova/src/globalConfig.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { defaultIsSSR } from '@alova/shared/vars';
import { AlovaGlobalConfig } from '~/typings';

export let globalConfigMap: Required<AlovaGlobalConfig> = {
autoHitCache: 'global'
autoHitCache: 'global',
ssr: defaultIsSSR
};

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/alova/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { default as Method } from './Method';
export { createAlova } from './alova';
export * from './functions/manipulateCache';
export { default as globalConfig } from './globalConfig';
export { default as globalConfig, globalConfigMap } from './globalConfig';
export { default as Method } from './Method';
export { promiseStatesHook } from './utils/helper';
17 changes: 17 additions & 0 deletions packages/alova/test/browser/global/ssr.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import globalConfig, { globalConfigMap } from '@/globalConfig';

describe('ssr', () => {
test('default ssr option', () => {
expect(globalConfigMap.ssr).toBeFalsy();
});

test('set ssr to false', () => {
globalConfig({ ssr: false });
expect(globalConfigMap.ssr).toBeFalsy();
});

test('set ssr to true', () => {
globalConfig({ ssr: true });
expect(globalConfigMap.ssr).toBeTruthy();
});
});
8 changes: 8 additions & 0 deletions packages/alova/typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,12 @@ export interface AlovaGlobalConfig {
* @default 'global'
*/
autoHitCache?: 'global' | 'self' | 'close';
/**
* whether the app is running in the server
* If not set or set to `undefined`, alova determines whether it is now running in the server
* @default undefined
*/
ssr?: boolean | undefined;
}

// ************ exports ***************
Expand Down Expand Up @@ -813,6 +819,8 @@ export declare function queryCache<AG extends AlovaGenerics>(
*/
export declare function hitCacheBySource<AG extends AlovaGenerics>(sourceMethod: Method<AG>): Promise<void>;

export declare const globalConfigMap: Required<AlovaGlobalConfig>;

/**
* Set global configuration
* @param config configuration
Expand Down
15 changes: 3 additions & 12 deletions packages/client/src/hooks/core/implements/createRequestState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,9 @@ import {
sloughConfig,
statesHookHelper
} from '@alova/shared/function';
import {
PromiseCls,
falseValue,
forEach,
isArray,
isSSR,
promiseCatch,
trueValue,
undefinedValue
} from '@alova/shared/vars';
import { PromiseCls, falseValue, forEach, isArray, promiseCatch, trueValue, undefinedValue } from '@alova/shared/vars';
import type { AlovaGlobalCacheAdapter, FrontRequestState, Method, Progress } from 'alova';
import { AlovaGenerics, promiseStatesHook } from 'alova';
import { AlovaGenerics, globalConfigMap, promiseStatesHook } from 'alova';
import {
AlovaCompleteEvent,
AlovaErrorEvent,
Expand Down Expand Up @@ -161,7 +152,7 @@ export default function createRequestState<AG extends AlovaGenerics, Config exte
);

// 在服务端渲染时不发送请求
if (!isSSR) {
if (!globalConfigMap.ssr) {
effectRequest({
handler:
// watchingStates为数组时表示监听状态(包含空数组),为undefined时表示不监听状态
Expand Down
6 changes: 3 additions & 3 deletions packages/client/src/hooks/useAutoRequest.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import useRequest from '@/hooks/core/useRequest';
import { noop, statesHookHelper } from '@alova/shared/function';
import { falseValue, isSSR, trueValue } from '@alova/shared/vars';
import { AlovaGenerics, Method, promiseStatesHook } from 'alova';
import { falseValue, trueValue } from '@alova/shared/vars';
import { AlovaGenerics, globalConfigMap, Method, promiseStatesHook } from 'alova';
import {
AlovaMethodHandler,
AutoRequestHookConfig,
Expand Down Expand Up @@ -69,7 +69,7 @@ const useAutoRequest: AutoRequestHook = (handler, config = {}) => {
let offVisiblity = noop;
let offPolling = noop;
onMounted(() => {
if (!isSSR) {
if (!globalConfigMap.ssr) {
offNetwork = enableNetwork ? useAutoRequest.onNetwork(notify, config) : offNetwork;
offFocus = enableFocus ? useAutoRequest.onFocus(notify, config) : offFocus;
offVisiblity = enableVisibility ? useAutoRequest.onVisibility(notify, config) : offVisiblity;
Expand Down
6 changes: 4 additions & 2 deletions packages/shared/src/vars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ export const defineProperty = (o: object, key: string | symbol, value: any, isDe
// 是否为服务端运行,node和bun通过process判断,deno通过Deno判断
// 部分框架(如支付宝和 uniapp)会注入 process 对象作为全局变量使用
// 因此使用服务端独有的 process.cwd 函数作为判断依据
export const isSSR =
typeof process !== undefStr ? typeof (process as any).cwd === 'function' : typeof Deno !== undefStr;
export const defaultIsSSR =
typeof window === undefStr &&
(typeof process !== undefStr ? typeof (process as any).cwd === 'function' : typeof Deno !== undefStr);
export const isSSR = defaultIsSSR;

/** cache mode */
// only cache in memory, it's default option
Expand Down
18 changes: 16 additions & 2 deletions packages/shared/test/isSSR.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@
const undefStr = 'undefined';
const MockGlobal: any = {};
const isSSR = () =>
typeof MockGlobal.process !== undefStr
typeof MockGlobal.window === undefStr &&
(typeof MockGlobal.process !== undefStr
? typeof MockGlobal.process.cwd === 'function'
: typeof MockGlobal.Deno !== undefStr;
: typeof MockGlobal.Deno !== undefStr);

const setGlobalWindow = (window: any) => {
MockGlobal.window = window;
};

const setGlobalProcess = (process: any) => {
MockGlobal.process = process;
Expand All @@ -16,6 +21,7 @@ const setGlobalDeno = (deno: any) => {

// Mock the global process and Deno objects before each test
beforeEach(() => {
delete MockGlobal.window;
delete MockGlobal.process;
delete MockGlobal.Deno;
});
Expand All @@ -28,6 +34,14 @@ describe('isSSR', () => {
expect(isSSR()).toBeFalsy();
});

it('should return false in codesandbox environment', () => {
// Browser: process is undefined, Deno is undefined
setGlobalWindow({});
setGlobalProcess({ cwd: () => 'test' });
setGlobalDeno(undefined);
expect(isSSR()).toBeFalsy();
});

it('should return false in react-native environment', () => {
// React Native: process is undefined, Deno is undefined
setGlobalProcess(undefined);
Expand Down

0 comments on commit 5c5b7db

Please sign in to comment.