Skip to content
This repository was archived by the owner on Mar 20, 2023. It is now read-only.

Allow custom graphql params extraction from request #730

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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: 28 additions & 0 deletions src/__tests__/http-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,34 @@ function runTests(server: Server) {
});
});

it('allow custom graphql params extraction from request', async () => {
const app = server();

app.get(
urlString(),
graphqlHTTP({
schema: TestSchema,
customGraphQLParamsFn: (request) => {
const searchParams = new URLSearchParams(request.url.split('?')[1]);
return {
query: searchParams.get('graphqlQuery'),
variables: null,
operationName: null,
raw: false,
};
},
}),
);

const response = await app.request().get(
urlString({
graphqlQuery: '{test}',
}),
);

expect(response.text).to.equal('{"data":{"test":"Hello World"}}');
});

describe('Pretty printing', () => {
it('supports pretty printing', async () => {
const app = server();
Expand Down
76 changes: 40 additions & 36 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ export interface OptionsData {
*/
customParseFn?: (source: Source) => DocumentNode;

/**
* An optional function which will get params from request instead of
* default getGraphQLParams
*/
customGraphQLParamsFn?: (
request: Request,
) => GraphQLParams | Promise<GraphQLParams>;

/**
* `formatError` is deprecated and replaced by `customFormatErrorFn`. It will
* be removed in version 1.0.0.
Expand Down Expand Up @@ -206,29 +214,34 @@ export function graphqlHTTP(options: Options): Middleware {
let params: GraphQLParams | undefined;
let showGraphiQL = false;
let graphiqlOptions;
let formatErrorFn = formatError;
let pretty = false;
let result: ExecutionResult;
let optionsData: OptionsData | undefined;

try {
// Parse the Request to get GraphQL request parameters.
try {
params = await getGraphQLParams(request);
} catch (error: unknown) {
// When we failed to parse the GraphQL parameters, we still need to get
// the options object, so make an options call to resolve just that.
optionsData = await resolveOptions();
pretty = optionsData.pretty ?? false;
formatErrorFn =
optionsData.customFormatErrorFn ??
optionsData.formatError ??
formatErrorFn;
throw error;
if (typeof options === 'function') {
try {
// Parse the Request to get GraphQL request parameters.
params = await getGraphQLParams(request);
} catch (error: unknown) {
// When we failed to parse the GraphQL parameters, we still need to get
// the options object, so make an options call to resolve just that.
optionsData = await options(request, response);
validateOptions();
throw error;
}
optionsData = await options(request, response, params);
validateOptions();
} else {
optionsData = await options;
validateOptions();
}

// Then, resolve the Options to get OptionsData.
optionsData = await resolveOptions(params);
if (optionsData.customGraphQLParamsFn) {
params = await optionsData.customGraphQLParamsFn(request);
} else if (!params) {
// Parse the Request to get GraphQL request parameters.
params = await getGraphQLParams(request);
}

// Collect information from the options data object.
const schema = optionsData.schema;
Expand All @@ -243,12 +256,6 @@ export function graphqlHTTP(options: Options): Middleware {
const executeFn = optionsData.customExecuteFn ?? execute;
const validateFn = optionsData.customValidateFn ?? validate;

pretty = optionsData.pretty ?? false;
formatErrorFn =
optionsData.customFormatErrorFn ??
optionsData.formatError ??
formatErrorFn;

// Assert that schema is required.
devAssert(
schema != null,
Expand Down Expand Up @@ -374,6 +381,7 @@ export function graphqlHTTP(options: Options): Middleware {
rawError instanceof Error ? rawError : String(rawError),
);

// eslint-disable-next-line require-atomic-updates
response.statusCode = error.status;

const { headers } = error;
Expand All @@ -398,6 +406,12 @@ export function graphqlHTTP(options: Options): Middleware {
}
}

const pretty = optionsData?.pretty ?? false;
const formatErrorFn =
optionsData?.customFormatErrorFn ??
optionsData?.formatError ??
formatError;

if (result.errors != null || result.data == null) {
const handleRuntimeQueryErrorFn =
optionsData?.handleRuntimeQueryErrorFn ??
Expand Down Expand Up @@ -442,28 +456,18 @@ export function graphqlHTTP(options: Options): Middleware {
sendResponse(response, 'application/json', payload);
}

async function resolveOptions(
requestParams?: GraphQLParams,
): Promise<OptionsData> {
const optionsResult = await Promise.resolve(
typeof options === 'function'
? options(request, response, requestParams)
: options,
);

function validateOptions() {
devAssert(
optionsResult != null && typeof optionsResult === 'object',
optionsData != null && typeof optionsData === 'object',
'GraphQL middleware option function must return an options object or a promise which will be resolved to an options object.',
);

if (optionsResult.formatError) {
if (optionsData.formatError) {
// eslint-disable-next-line no-console
console.warn(
'`formatError` is deprecated and replaced by `customFormatErrorFn`. It will be removed in version 1.0.0.',
);
}

return optionsResult;
}
};
}
Expand Down