Skip to content
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

(core) - Shorten queries for hashing #911

Merged
merged 4 commits into from
Jul 21, 2020
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
5 changes: 5 additions & 0 deletions .changeset/hip-adults-look.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@urql/core': patch
---

Remove whitespace and comments from string-queries
14 changes: 14 additions & 0 deletions packages/core/src/utils/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,17 @@ it('should return a valid query object with variables', () => {
variables: { test: 5 },
});
});

it('should remove comments', () => {
const doc = `
{ #query
# broken
test
}
`;
const val = createRequest(doc);
expect(print(val.query)).toBe(`{
test
}
`);
});
6 changes: 4 additions & 2 deletions packages/core/src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ interface Documents {
[key: number]: DocumentNode;
}

const hashQuery = (q: string): number => hash(q.replace(/[\s,]+/g, ' ').trim());
const hashQuery = (q: string): number =>
hash(q.replace(/([\s,]|#[^\n\r]+)+/g, ' ').trim());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I wonder if we should confirm that hashes only ever occur after newline+whitespace (though I'm sure this should be okay)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wgolledge I've added a test


const docs: Documents = Object.create(null);

Expand All @@ -19,7 +20,8 @@ export const createRequest = (
let query: DocumentNode;
if (typeof q === 'string') {
key = hashQuery(q);
query = docs[key] !== undefined ? docs[key] : parse(q);
query =
docs[key] !== undefined ? docs[key] : parse(q, { noLocation: true });
} else if ((q as any).__key !== undefined) {
key = (q as any).__key;
query = q;
Expand Down