Skip to content

Add support for customValidateFn and rename formatError to customFormatErrorFn #146

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 27, 2021
Merged
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
20 changes: 13 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,6 @@ The `graphqlHTTP` function accepts the following options:

- **`pretty`**: If `true`, any JSON response will be pretty-printed.

- **`formatError`**: An optional function which will be used to format any
errors produced by fulfilling a GraphQL operation. If no function is
provided, GraphQL's default spec-compliant [`formatError`][] function will be used.

- **`extensions`**: An optional function for adding additional metadata to the
GraphQL response as a key-value object. The result will be added to
`"extensions"` field in the resulting JSON. This is often a useful place to
Expand All @@ -121,11 +117,21 @@ The `graphqlHTTP` function accepts the following options:
- **`validationRules`**: Optional additional validation rules queries must
satisfy in addition to those defined by the GraphQL spec.

- **`fieldResolver`**
- **`customValidateFn`**: An optional function which will be used to validate
instead of default `validate` from `graphql-js`.

- **`customExecuteFn`**: An optional function which will be used to execute
instead of default `execute` from `graphql-js`.

- **`customFormatErrorFn`**: An optional function which will be used to format any
errors produced by fulfilling a GraphQL operation. If no function is
provided, GraphQL's default spec-compliant [`formatError`][] function will be used.

- **`formatError`**: is deprecated and replaced by `customFormatErrorFn`. It will be
removed in version 1.0.0.

- **`fieldResolver`**

## HTTP Usage

Once installed at a path, `koa-graphql` will accept requests with
Expand Down Expand Up @@ -350,10 +356,10 @@ export function DisallowMetadataQueries(context) {
## Debugging Tips

During development, it's useful to get more information from errors, such as
stack traces. Providing a function to `formatError` enables this:
stack traces. Providing a function to `customFormatErrorFn` enables this:

```js
formatError: (error, ctx) => ({
customFormatErrorFn: (error, ctx) => ({
message: error.message,
locations: error.locations,
stack: error.stack ? error.stack.split('\n') : [],
Expand Down
108 changes: 108 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"prettier": "^2.3.2",
"raw-body": "^2.4.1",
"sane": "^4.1.0",
"sinon": "^11.1.2",
"supertest": "^4.0.2"
},
"peerDependencies": {
Expand Down
111 changes: 107 additions & 4 deletions src/__tests__/http-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import { expect } from 'chai';
import { describe, it } from 'mocha';
import sinon from 'sinon';
import { stringify } from 'querystring';
import zlib from 'zlib';
import multer from 'multer';
Expand All @@ -22,6 +23,7 @@ import {
GraphQLString,
GraphQLError,
BREAK,
validate,
execute,
} from 'graphql';
import graphqlHTTP from '../';
Expand Down Expand Up @@ -1144,7 +1146,7 @@ describe('GraphQL-HTTP tests', () => {
urlString(),
graphqlHTTP({
schema: TestSchema,
formatError(error) {
customFormatErrorFn(error) {
return { message: 'Custom error format: ' + error.message };
},
}),
Expand Down Expand Up @@ -1176,7 +1178,7 @@ describe('GraphQL-HTTP tests', () => {
urlString(),
graphqlHTTP({
schema: TestSchema,
formatError(error) {
customFormatErrorFn(error) {
return {
message: error.message,
locations: error.locations,
Expand Down Expand Up @@ -1422,7 +1424,7 @@ describe('GraphQL-HTTP tests', () => {
});
});

it('allows for custom error formatting of poorly formed requests', async () => {
it('`formatError` is deprecated', async () => {
const app = server();

app.use(
Expand All @@ -1437,6 +1439,47 @@ describe('GraphQL-HTTP tests', () => {
),
);

const spy = sinon.spy(console, 'warn');

const response = await request(app.listen()).get(
urlString({
variables: 'who:You',
query: 'query helloWho($who: String){ test(who: $who) }',
}),
);

expect(
spy.calledWith(
'`formatError` is deprecated and replaced by `customFormatErrorFn`. It will be removed in version 1.0.0.',
),
);
expect(response.status).to.equal(400);
expect(JSON.parse(response.text)).to.deep.equal({
errors: [
{
message: 'Custom error format: Variables are invalid JSON.',
},
],
});

spy.restore();
});

it('allows for custom error formatting of poorly formed requests', async () => {
const app = server();

app.use(
mount(
urlString(),
graphqlHTTP({
schema: TestSchema,
customFormatErrorFn(error) {
return { message: 'Custom error format: ' + error.message };
},
}),
),
);

const response = await request(app.listen()).get(
urlString({
variables: 'who:You',
Expand Down Expand Up @@ -1832,6 +1875,66 @@ describe('GraphQL-HTTP tests', () => {
});
});

describe('Custom validate function', () => {
it('returns data', async () => {
const app = server();

app.use(
mount(
urlString(),
graphqlHTTP({
schema: TestSchema,
customValidateFn(schema, documentAST, validationRules) {
return validate(schema, documentAST, validationRules);
},
}),
),
);

const response = await request(app.listen())
.get(urlString({ query: '{test}', raw: '' }))
.set('Accept', 'text/html');

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

it('returns validation errors', async () => {
const app = server();

app.use(
mount(
urlString(),
graphqlHTTP({
schema: TestSchema,
customValidateFn(schema, documentAST, validationRules) {
const errors = validate(schema, documentAST, validationRules);

const error = new GraphQLError(`custom error ${errors.length}`);

return [error];
},
}),
),
);

const response = await request(app.listen()).get(
urlString({
query: '{thrower}',
}),
);

expect(response.status).to.equal(400);
expect(JSON.parse(response.text)).to.deep.equal({
errors: [
{
message: 'custom error 0',
},
],
});
});
});

describe('Custom validation rules', () => {
const AlwaysInvalidRule = function (context) {
return {
Expand Down Expand Up @@ -1963,7 +2066,7 @@ describe('GraphQL-HTTP tests', () => {
urlString(),
graphqlHTTP({
schema: TestSchema,
formatError: () => null,
customFormatErrorFn: () => null,
extensions({ result }) {
return { preservedErrors: (result: any).errors };
},
Expand Down
Loading