Last active
July 9, 2022 08:42
-
-
Save kylemocode/a9b1e3bd7925614cc93b1121271cfd5e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { addMocksToSchema, Ref } from '@graphql-tools/mock'; | |
import type { ExecutionResult, IntrospectionQuery } from 'graphql'; | |
import { buildClientSchema, graphql } from 'graphql'; | |
import { graphql as mswGraphql } from 'msw'; | |
import IntrospectionResultData from '@/generated/introspection.json'; | |
const schema = buildClientSchema( | |
(IntrospectionResultData as unknown) as IntrospectionQuery | |
); | |
/* 這邊可以指定特定的 GraphQL Type 想要回傳什麼資料 */ | |
const mocks = { | |
URL: () => 'https://example.com', | |
DateTime: () => '2022-07-11T11:43:31.000-0430', | |
}; | |
export const schemaWithMocks = addMocksToSchema({ | |
schema, | |
mocks | |
}); | |
export default function handleRequest( | |
query: string, | |
variables: Record<string, string> | |
): Promise<ExecutionResult> { | |
return graphql({ | |
schema: schemaWithMocks, | |
source: query, | |
variableValues: variables, | |
}); | |
} | |
export const handler = mswGraphql | |
.link('your graphql URL') | |
.operation(async (req, res, ctx) => { | |
const { body } = req; | |
if (!body) { | |
throw new Error('Request body missing'); | |
} | |
const payload = await handleRequest(body.query, req.variables); | |
if (payload.errors) { | |
return res(ctx.errors([...payload.errors])); | |
} | |
return res(ctx.data(payload.data || {})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment