Skip to content

Commit

Permalink
fix: Fetch handler hacks for Mirage (#9199)
Browse files Browse the repository at this point in the history
* Allow `store.request` to be intercepted by Mirage

* Don't `cloneResponse` for Mirage mock responses

Mirage mock responses don't properly include a body stream.
  • Loading branch information
gitKrystan authored Jan 10, 2024
1 parent 5ed8497 commit 3990cc1
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions packages/request/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@
* @module @ember-data/request/fetch
* @main @ember-data/request/fetch
*/
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 @@ -30,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 @@ -115,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

0 comments on commit 3990cc1

Please sign in to comment.