Skip to content

Commit

Permalink
Introduce usage reporting signature and its components (#92)
Browse files Browse the repository at this point in the history
This commit introduces a new `@apollo/utils.usagereporting` package
which exports common bits of usage reporting code shared between
apollo-server and router-bridge.

Consequently, this also introduces and updates a couple other related packages:
`@apollo/utils.removealiases`
`@apollo/utils.stripsensitiveliterals`

These transforms are used by `usagereporting` in order to derive the operation
signature.

For testing purposes, I've also introduced a snapshot serializer for printing
GraphQL AST nodes.
`@apollo/utils.jest-graphql-ast-serializer`

Related: apollographql/federation#1841
  • Loading branch information
trevor-scheer authored May 19, 2022
1 parent 75b36b7 commit 0d9db54
Show file tree
Hide file tree
Showing 41 changed files with 1,879 additions and 655 deletions.
9 changes: 9 additions & 0 deletions .changeset/sour-berries-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@apollo/utils.jest-graphql-ast-serializer": major
"@apollo/utils.removealiases": major
"@apollo/utils.stripsensitiveliterals": minor
"@apollo/utils.usagereporting": major
---

Initial release of usage reporting signature (and its components)
Initial release of calculateReferencedFieldsByType
1,218 changes: 645 additions & 573 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
"@changesets/cli": "2.22.0",
"@jest/types": "28.1.0",
"@types/bunyan": "1.8.8",
"@types/jest": "27.5.1",
"@types/lodash.sortby": "4.7.7",
"@types/make-fetch-happen": "9.0.2",
"@types/node": "12.20.52",
Expand Down
7 changes: 7 additions & 0 deletions packages/jestGraphQLASTSerializer/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
*
!src/**/*
!dist/**/*
dist/**/*.test.*
!package.json
!README.md
!LICENSE
21 changes: 21 additions & 0 deletions packages/jestGraphQLASTSerializer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Apollo Graph, Inc. (Formerly Meteor Development Group, Inc.)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
11 changes: 11 additions & 0 deletions packages/jestGraphQLASTSerializer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# graphQLASTSerializer

For snapshot testing in graphql, seeing the printed document is a concise and human-readable approach to validating AST objects. Installing this serializer means that all GraphQL document ASTs will be printed into the snapshot using the `graphql-js` `print` function rather than printing out the entire AST object (which would be the default behavior).

You can use it in your test files like so:

```ts
import graphQLASTSerializer from "@apollo/utils.jest-graphql-ast-serializer";

expect.addSnapshotSerializer(graphQLASTSerializer);
```
9 changes: 9 additions & 0 deletions packages/jestGraphQLASTSerializer/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import baseConfig from "../../jest.config.base";

export default {
...baseConfig,
displayName: {
name: "graphQLASTSerializer",
color: "green",
},
};
30 changes: 30 additions & 0 deletions packages/jestGraphQLASTSerializer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "@apollo/utils.jest-graphql-ast-serializer",
"version": "0.0.0",
"description": "A Jest snapshot serializer for GraphQL ASTs",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/apollographql/apollo-utils.git",
"directory": "packages/jestGraphQLASTSerializer/"
},
"keywords": [
"apollo",
"graphql",
"jest",
"typescript",
"node"
],
"author": "Apollo <[email protected]>",
"license": "MIT",
"engines": {
"node": ">=12.13.0"
},
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"graphql": "14.x || 15.x || 16.x"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { parse } from "graphql";
import graphQLASTSerializer from "../../dist";

describe("graphQLASTSerializer", () => {
const ast = parse(`query Foo { test }`);
const invalidAST = { kind: "invalid" };

it("correctly identifies GraphQL AST nodes", () => {
expect(graphQLASTSerializer.test(ast)).toBe(true);
expect(graphQLASTSerializer.test(ast.definitions[0])).toBe(true);
});

it("correctly identifies non-AST nodes", () => {
expect(graphQLASTSerializer.test("a string")).toBe(false);
expect(graphQLASTSerializer.test(1)).toBe(false);
expect(graphQLASTSerializer.test(invalidAST)).toBe(false);
});

it("serializes AST nodes", () => {
expect(graphQLASTSerializer.serialize(ast)).toMatchInlineSnapshot(`
"query Foo {
test
}"
`);
});

it("throws on malformed AST", () => {
expect(() =>
// @ts-expect-error
graphQLASTSerializer.serialize(invalidAST),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid AST Node: { kind: \\"invalid\\" }."`,
);
});
});
5 changes: 5 additions & 0 deletions packages/jestGraphQLASTSerializer/src/__tests__/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "../../../../tsconfig.test.base",
"include": ["**/*"],
"references": [{ "path": "../../" }]
}
16 changes: 16 additions & 0 deletions packages/jestGraphQLASTSerializer/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ASTNode, print } from "graphql";
import { isNode } from "graphql/language/ast";

// This is exported as a default so that it can (hopefully one day) be picked up
// by Jest's `snapshotSerializers` config option. For now, Jest doesn't
// correctly unwrap default exports when providing the name of a module in this
// manner.
export default {
test(value: any) {
return isNode(value);
},

serialize(value: ASTNode): string {
return print(value);
},
};
9 changes: 9 additions & 0 deletions packages/jestGraphQLASTSerializer/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist"
},
"include": ["src/**/*"],
"exclude": ["**/__tests__"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,27 @@ import gql from "graphql-tag";
import { printWithReducedWhitespace } from "..";

describe("printWithReducedWhitespace", () => {
const cases = [
{
name: "lots of whitespace",
// Note: there's a tab after "tab->", which prettier wants to keep as a
// literal tab rather than \t. In the output, there should be a literal
// backslash-t.
input: gql`
query Foo($a: Int) {
user(
name: " tab-> yay"
other: """
apple
bag
cat
"""
) {
name
}
it("removes whitespace", () => {
// Note: there's a tab after "tab->", which prettier wants to keep as a
// literal tab rather than \t. In the output, there should be a literal
// backslash-t.
const document = gql`
query Foo($a: Int) {
user(
name: " tab-> yay"
other: """
apple
bag
cat
"""
) {
name
}
`,
output:
'query Foo($a:Int){user(name:" tab->\\tyay"other:"apple\\n bag\\ncat"){name}}',
},
];
cases.forEach(({ name, input, output }) => {
test(name, () => {
expect(printWithReducedWhitespace(input)).toEqual(output);
});
}
`;

expect(printWithReducedWhitespace(document)).toBe(
`query Foo($a:Int){user(name:" tab->\\tyay"other:"apple\\n bag\\ncat"){name}}`,
);
});
});
7 changes: 7 additions & 0 deletions packages/removeAliases/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
*
!src/**/*
!dist/**/*
dist/**/*.test.*
!package.json
!README.md
!LICENSE
21 changes: 21 additions & 0 deletions packages/removeAliases/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Apollo Graph, Inc. (Formerly Meteor Development Group, Inc.)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
12 changes: 12 additions & 0 deletions packages/removeAliases/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# removeAliases

The `removeAliases` function is a `graphql-js` visitor which removes aliases from all `Field` nodes. Note that this function makes no guarantees about the output being a valid GraphQL operation.

For example, the following operation is no longer valid once the alias is removed since the fields can't be merged:

```graphql
query {
x(a: 1)
alias: x(a: 2)
}
```
9 changes: 9 additions & 0 deletions packages/removeAliases/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import baseConfig from "../../jest.config.base";

export default {
...baseConfig,
displayName: {
name: "removeAliases",
color: "yellow",
},
};
29 changes: 29 additions & 0 deletions packages/removeAliases/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@apollo/utils.removealiases",
"version": "0.0.0",
"description": "Remove aliases from a GraphQL document",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/apollographql/apollo-utils.git",
"directory": "packages/removeAliases/"
},
"keywords": [
"apollo",
"graphql",
"typescript",
"node"
],
"author": "Apollo <[email protected]>",
"license": "MIT",
"engines": {
"node": ">=12.13.0"
},
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"graphql": "14.x || 15.x || 16.x"
}
}
39 changes: 39 additions & 0 deletions packages/removeAliases/src/__tests__/removeAliases.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import gql from "graphql-tag";
import { removeAliases } from "..";

import graphQLASTSerializer from "@apollo/utils.jest-graphql-ast-serializer";
expect.addSnapshotSerializer(graphQLASTSerializer);

describe("removeAliases", () => {
it("removes aliases from Field nodes", () => {
expect(
removeAliases(gql`
query MyQuery {
alias: field
field
fieldWithSelections {
selection1
selection2
}
aliasedSelections: fieldWithSelections {
selection1
selection2
}
}
`),
).toMatchInlineSnapshot(`
query MyQuery {
field
field
fieldWithSelections {
selection1
selection2
}
fieldWithSelections {
selection1
selection2
}
}
`);
});
});
12 changes: 12 additions & 0 deletions packages/removeAliases/src/__tests__/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "../../../../tsconfig.test.base",
"include": ["**/*"],
"references": [
{
"path": "../../"
},
{
"path": "../../../jestGraphQLASTSerializer"
}
]
}
17 changes: 17 additions & 0 deletions packages/removeAliases/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// removeAliases gets rid of GraphQL aliases, a feature by which you can tell a
// server to return a field's data under a different name from the field name.
// Maybe this is useful if somebody somewhere inserts random aliases into their
// queries. Note that this function makes no guarantees about the output and its
// validity as a GraphQL operation, for example:
// { x(a: 1) alias: x(a:2) } (valid) will yield
// { x(a:1) x(a:2) } (invalid)
import { DocumentNode, FieldNode, visit } from "graphql";

export function removeAliases(ast: DocumentNode): DocumentNode {
return visit(ast, {
Field(node: FieldNode): FieldNode {
const { alias, ...rest } = node;
return rest;
},
});
}
10 changes: 10 additions & 0 deletions packages/removeAliases/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist"
},
"include": ["src/**/*"],
"exclude": ["**/__tests__"],
"references": []
}
Loading

0 comments on commit 0d9db54

Please sign in to comment.