Last active
February 20, 2018 20:03
-
-
Save awwong1/5c7ad32c95304e0f40987a9ac708691d to your computer and use it in GitHub Desktop.
ValidationError GraphQL
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 { GraphQLError } from 'graphql'; | |
class ValidationError extends GraphQLError { | |
constructor(errors) { | |
super('The request is invalid.'); | |
this.state = errors.reduce((result, error) => { | |
if (Object.prototype.hasOwnProperty.call(result, error.key)) { | |
result[error.key].push(error.message); | |
} else { | |
result[error.key] = [error.message]; | |
} | |
return result; | |
}, {}); | |
} | |
} | |
export default ValidationError; | |
// However, this Jest test currently fails | |
describe("Errors", () => { | |
it("should check equality on state", done => { | |
expect(new ValidationError([{ key: "key", message: "test" }])).not.toEqual( | |
new ValidationError() | |
); | |
done(); | |
}); | |
}); | |
``` | |
● Errors › should check equality on state | |
expect(received).not.toEqual(expected) | |
Expected value to not equal: | |
[GraphQLError: The request is invalid.] | |
Received: | |
[GraphQLError: The request is invalid.] | |
5 | expect( | |
6 | new ValidationError([{ key: "key", message: "test" }]) | |
> 7 | ).not.toEqual(new ValidationError); | |
8 | done(); | |
9 | }); | |
10 | }); | |
at Object.done (__test__/modules/Errors.test.js:7:9) | |
``` | |
// gross workaround | |
class ValidationError extends GraphQLError { | |
constructor(errors=[]) { | |
let state = errors.reduce((result, error) => { | |
if (Object.prototype.hasOwnProperty.call(result, error.key)) { | |
result[error.key].push(error.message); | |
} else { | |
result[error.key] = [error.message]; | |
} | |
return result; | |
}, {}); | |
super("The request is invalid. " + JSON.stringify(state)); | |
this.state = state; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment