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

fix: Fetch handler hacks for Mirage (canary) #9203

Merged
merged 1 commit into from
Jan 16, 2024
Merged
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
28 changes: 21 additions & 7 deletions packages/request/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@
* @module @ember-data/request/fetch
* @main @ember-data/request/fetch
*/
import type { HttpErrorProps } from '-private/utils';
import { getOwnConfig, macroCondition } from '@embroider/macros';

import { cloneResponseProperties, type Context } from './-private/context';
import type { HttpErrorProps } from './-private/utils';

// Lazily close over fetch to avoid breaking Mirage
const _fetch: typeof fetch =
typeof fetch !== 'undefined'
? fetch
? (...args) => fetch(...args)
: typeof FastBoot !== 'undefined'
? (FastBoot.require('node-fetch') as typeof fetch)
? (...args) => (FastBoot.require('node-fetch') as typeof fetch)(...args)
: ((() => {
throw new Error('No Fetch Implementation Found');
}) as typeof fetch);
Expand All @@ -31,6 +33,12 @@ function cloneResponse(response: Response, overrides: Partial<Response>) {
return new Response(response.body, Object.assign(props, overrides));
}

let IS_MAYBE_MIRAGE = () => false;
if (macroCondition(getOwnConfig<{ env: { TESTING: boolean } }>().env.TESTING)) {
IS_MAYBE_MIRAGE = () =>
Boolean(typeof window !== 'undefined' && (window as { server?: { pretender: unknown } }).server?.pretender);
}

const MUTATION_OPS = new Set(['updateRecord', 'createRecord', 'deleteRecord']);
const ERROR_STATUS_CODE_FOR = new Map([
[400, 'Bad Request'],
Expand Down Expand Up @@ -94,7 +102,7 @@ const ERROR_STATUS_CODE_FOR = new Map([
*/
const Fetch = {
async request(context: Context) {
let response;
let response: Response;

try {
response = await _fetch(context.request.url!, context.request);
Expand All @@ -116,9 +124,15 @@ const Fetch = {
const isMutationOp = Boolean(op && MUTATION_OPS.has(op));

if (!isError && !isMutationOp && response.status !== 204 && !response.headers.has('date')) {
const headers = new Headers(response.headers);
headers.set('date', new Date().toUTCString());
response = cloneResponse(response, { headers });
if (IS_MAYBE_MIRAGE()) {
response.headers.set('date', new Date().toUTCString());
} else {
const headers = new Headers(response.headers);
headers.set('date', new Date().toUTCString());
response = cloneResponse(response, {
headers,
});
}
}

context.setResponse(response);
Expand Down
Loading