Skip to content

Commit

Permalink
feat(graphql): escape queries with variables
Browse files Browse the repository at this point in the history
  • Loading branch information
mefellows committed Apr 29, 2018
1 parent c378c8c commit 8b64dd4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
36 changes: 29 additions & 7 deletions src/dsl/graphql.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,22 +73,44 @@ describe("GraphQLInteraction", () => {
});
});

describe("when given a valid valid query", () => {
describe("when given a valid query", () => {
it("should properly marshal the query", () => {
const json: any = interaction.json();
expect(isMatcher(json.request.body.query)).to.eq(true);
expect(json.request.body.query.getValue()).to.eq("{ hello }");
});

it("should add regular expressions for the whitespace in the query", () => {
const json: any = interaction.json();
describe("without variables", () => {
it("should add regular expressions for the whitespace in the query", () => {
const json: any = interaction.json();

expect(isMatcher(json.request.body.query)).to.eq(true);
const r = new RegExp(json.request.body.query.data.matcher.s, "g");
const lotsOfWhitespace = `{ hello
expect(isMatcher(json.request.body.query)).to.eq(true);
const r = new RegExp(json.request.body.query.data.matcher.s, "g");
const lotsOfWhitespace = `{ hello
}`;
expect(r.test(lotsOfWhitespace)).to.eq(true);
expect(r.test(lotsOfWhitespace)).to.eq(true);
});
});

describe("and variables", () => {
it("should add regular expressions for the whitespace in the query", () => {
interaction.withQuery(`{
Hello(id: $id) {
name
}
}`);
interaction.withVariables({
name: "bar",
});
const json: any = interaction.json();

expect(isMatcher(json.request.body.query)).to.eq(true);
const r = new RegExp(json.request.body.query.data.matcher.s, "g");
const lotsOfWhitespace = `{ Hello(id: \$id) { name } }`;
expect(r.test(lotsOfWhitespace)).to.eq(true);
});

});
});
});
Expand Down
8 changes: 7 additions & 1 deletion src/dsl/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export class GraphQLInteraction extends Interaction {
this.state.request = extend({
body: {
operationName: this.operation,
query: regex({ generate: this.query, matcher: this.query.replace(/\s+/g, "\\s*") }),
query: regex({ generate: this.query, matcher: escapeGraphQlQuery(this.query) }),
variables: this.variables,
},
headers: { "content-type": "application/json" },
Expand All @@ -106,3 +106,9 @@ export class GraphQLInteraction extends Interaction {
return this.state;
}
}

const escapeGraphQlQuery = (s: string) => escapeSpace(escapeRegexChars(s));

const escapeRegexChars = (s: string) => s.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

const escapeSpace = (s: string) => s.replace(/\s+/g, "\\s*");

0 comments on commit 8b64dd4

Please sign in to comment.