|
| 1 | +import { hashObject } from '@graphql-mesh/string-interpolation'; |
| 2 | +import { MeshPlugin, MeshPluginOptions, YamlConfig } from '@graphql-mesh/types'; |
| 3 | +import { getHeadersObj, pathExists, writeJSON } from '@graphql-mesh/utils'; |
| 4 | +import minimatch from 'minimatch'; |
| 5 | +import { fs, path, process } from '@graphql-mesh/cross-helpers'; |
| 6 | +import { Response } from '@whatwg-node/fetch'; |
| 7 | + |
| 8 | +function calculateCacheKey(url: string, options: RequestInit) { |
| 9 | + return hashObject({ |
| 10 | + url, |
| 11 | + options, |
| 12 | + }); |
| 13 | +} |
| 14 | + |
| 15 | +interface SnapshotEntry { |
| 16 | + text: string; |
| 17 | + headersObj: Record<string, string>; |
| 18 | + status: number; |
| 19 | + statusText: string; |
| 20 | +} |
| 21 | + |
| 22 | +export default function useSnapshot( |
| 23 | + pluginOptions: MeshPluginOptions<YamlConfig.SnapshotPluginConfig> |
| 24 | +): MeshPlugin<any> { |
| 25 | + if (typeof pluginOptions.if === 'boolean') { |
| 26 | + if (!pluginOptions.if) { |
| 27 | + return {}; |
| 28 | + } |
| 29 | + } |
| 30 | + if (typeof pluginOptions.if === 'string') { |
| 31 | + // eslint-disable-next-line no-new-func |
| 32 | + if (new Function('return ' + pluginOptions.if, 'env')(process.env)) { |
| 33 | + return {}; |
| 34 | + } |
| 35 | + } |
| 36 | + const matches = pluginOptions.apply.map(glob => new minimatch.Minimatch(glob)); |
| 37 | + const snapshotsDir = pluginOptions.outputDir || '__snapshots__'; |
| 38 | + return { |
| 39 | + async onFetch({ url, options, setFetchFn }) { |
| 40 | + if (matches.some(matcher => matcher.match(url))) { |
| 41 | + const snapshotFileName = calculateCacheKey(url, options); |
| 42 | + const snapshotPath = path.join(pluginOptions.baseDir, snapshotsDir, `${snapshotFileName}.json`); |
| 43 | + if (await pathExists(snapshotPath)) { |
| 44 | + setFetchFn(async () => { |
| 45 | + const snapshotFile = await fs.promises.readFile(snapshotPath, 'utf-8'); |
| 46 | + const snapshot: SnapshotEntry = JSON.parse(snapshotFile); |
| 47 | + return new Response(snapshot.text, { |
| 48 | + headers: snapshot.headersObj, |
| 49 | + status: snapshot.status, |
| 50 | + statusText: snapshot.statusText, |
| 51 | + }); |
| 52 | + }); |
| 53 | + return () => {}; |
| 54 | + } |
| 55 | + return async ({ response, setResponse }) => { |
| 56 | + const snapshot: SnapshotEntry = { |
| 57 | + text: await response.text(), |
| 58 | + headersObj: getHeadersObj(response.headers), |
| 59 | + status: response.status, |
| 60 | + statusText: response.statusText, |
| 61 | + }; |
| 62 | + await writeJSON(snapshotPath, snapshot); |
| 63 | + setResponse( |
| 64 | + new Response(snapshot.text, { |
| 65 | + headers: snapshot.headersObj, |
| 66 | + status: snapshot.status, |
| 67 | + statusText: snapshot.statusText, |
| 68 | + }) |
| 69 | + ); |
| 70 | + }; |
| 71 | + } |
| 72 | + return () => {}; |
| 73 | + }, |
| 74 | + }; |
| 75 | +} |
0 commit comments