File size: 2,273 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import type { Preview } from '@storybook/react'
import DefaultDecorator from '../web/src/app/storybook/decorators'
import { initialize, mswLoader } from 'msw-storybook-addon'
import { defaultConfig } from '../web/src/app/storybook/graphql'
import { graphql, HttpResponse } from 'msw'

initialize({
  onUnhandledRequest: 'bypass',
})

export type GraphQLRequestHandler = (variables: unknown) => object
export type GraphQLParams = Record<string, GraphQLRequestHandler>

const componentConfig: Record<string, GraphQLParams> = {}

export const mswHandler = graphql.operation((params) => {
  const url = new URL(params.request.url)
  const gql = componentConfig[url.pathname]
  const handler = gql[params.operationName]
  if (!handler) {
    return HttpResponse.json({
      errors: [
        { message: `No mock defined for operation '${params.operationName}'.` },
      ],
    })
  }

  if (typeof handler === 'function') {
    return HttpResponse.json(handler(params.variables))
  }

  return HttpResponse.json(handler)
})

interface LoaderArg {
  id: string
  parameters: {
    graphql?: GraphQLParams
  }
}

/**
 * graphqlLoader is a loader function that sets up the GraphQL mocks for the
 * component. It stores them in a global object, componentConfig, which is used
 * by the mswHandler to resolve the mocks.
 *
 * We need to do this because the browser will render all components at once,
 * and so we need to handle all GraphQL mocks at once.
 *
 * The way this works is that each component get's a unique URL for GraphQL
 * (see decorators.tsx). This URL is used to store the GraphQL mocks for that
 * component in componentConfig.
 */
export function graphQLLoader(arg: LoaderArg): void {
  const path = '/' + encodeURIComponent(arg.id) + '/api/graphql'
  componentConfig[path] = arg.parameters.graphql || {}
}

const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
    graphql: {
      // default GraphQL handlers
      RequireConfig: { data: defaultConfig },
      useExpFlag: { data: { experimentalFlags: [] } },
    },
    msw: { handlers: [mswHandler] },
  },
  decorators: [DefaultDecorator],
  loaders: [graphQLLoader, mswLoader],
}

export default preview