-
-
Notifications
You must be signed in to change notification settings - Fork 676
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b2822d8
commit b815600
Showing
24 changed files
with
2,839 additions
and
3 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
--- | ||
title: Bootstrapping | ||
id: version-1.0.0-rc.1-bootstrap | ||
original_id: bootstrap | ||
--- | ||
|
||
After creating our resolvers, type classes, and other business-related code, we need to make our app run. First we have to build the schema, then we can expose it with an HTTP server, WebSockets or even MQTT. | ||
|
||
## Create Executable Schema | ||
|
||
To create an executable schema from type and resolver definitions, we need to use the `buildSchema` function. | ||
It takes a configuration object as a parameter and returns a promise of a `GraphQLSchema` object. | ||
|
||
In the configuration object we must provide a `resolvers` property, which can be an array of resolver classes: | ||
|
||
```typescript | ||
import { FirstResolver, SecondResolver } from "../app/src/resolvers"; | ||
// ... | ||
const schema = await buildSchema({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
``` | ||
|
||
Be aware that only operations (queries, mutation, etc.) defined in the resolvers classes (and types directly connected to them) will be emitted in schema. | ||
|
||
So if we have defined some object types (that implements an interface type [with disabled auto registering](interfaces.md#registering-in-schema)) but are not directly used in other types definition (like a part of an union, a type of a field or a return type of an operation), we need to provide them manually in `orphanedTypes` options of `buildSchema`: | ||
|
||
```typescript | ||
import { FirstResolver, SecondResolver } from "../app/src/resolvers"; | ||
import { FirstObject } from "../app/src/types"; | ||
// ... | ||
const schema = await buildSchema({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
// here provide all the types that are missing in schema | ||
orphanedTypes: [FirstObject], | ||
}); | ||
``` | ||
|
||
However, when there are several resolver classes, manual imports can be cumbersome. | ||
So we can also provide an array of paths to resolver module files instead, which can include globs: | ||
|
||
```typescript | ||
const schema = await buildSchema({ | ||
resolvers: [__dirname + "/modules/**/*.resolver.{ts,js}", __dirname + "/resolvers/**/*.{ts,js}"], | ||
}); | ||
``` | ||
|
||
> Be aware that in case of providing paths to resolvers files, TypeGraphQL will emit all the operations and types that are imported in the resolvers files or their dependencies. | ||
There are also other options related to advanced features like [authorization](authorization.md) or [validation](validation.md) - you can read about them in docs. | ||
|
||
To make `await` work, we need to declare it as an async function. Example of `main.ts` file: | ||
|
||
```typescript | ||
import { buildSchema } from "type-graphql"; | ||
|
||
async function bootstrap() { | ||
const schema = await buildSchema({ | ||
resolvers: [__dirname + "/**/*.resolver.{ts,js}"], | ||
}); | ||
|
||
// other initialization code, like creating http server | ||
} | ||
|
||
bootstrap(); // actually run the async function | ||
``` | ||
|
||
## Create an HTTP GraphQL endpoint | ||
|
||
In most cases, the GraphQL app is served by an HTTP server. After building the schema we can create the GraphQL endpoint with a variety of tools such as [`graphql-yoga`](https://github.com/prisma/graphql-yoga) or [`apollo-server`](https://github.com/apollographql/apollo-server). Here is an example using [`apollo-server`](https://github.com/apollographql/apollo-server): | ||
|
||
```typescript | ||
import { ApolloServer } from "apollo-server"; | ||
|
||
const PORT = process.env.PORT || 4000; | ||
|
||
async function bootstrap() { | ||
// ... Building schema here | ||
|
||
// Create the GraphQL server | ||
const server = new ApolloServer({ | ||
schema, | ||
playground: true, | ||
}); | ||
|
||
// Start the server | ||
const { url } = await server.listen(PORT); | ||
console.log(`Server is running, GraphQL Playground available at ${url}`); | ||
} | ||
|
||
bootstrap(); | ||
``` | ||
|
||
Remember to install the `apollo-server` package from npm - it's not bundled with TypeGraphQL. | ||
|
||
Of course you can use the `express-graphql` middleware, `graphql-yoga` or whatever you want 😉 | ||
|
||
## Create typeDefs and resolvers map | ||
|
||
TypeGraphQL provides a second way to generate the GraphQL schema - the `buildTypeDefsAndResolvers` function. | ||
|
||
It accepts the same `BuildSchemaOptions` as the `buildSchema` function but instead of an executable `GraphQLSchema`, it creates a typeDefs and resolversMap pair that you can use e.g. with [`graphql-tools`](https://github.com/apollographql/graphql-tools): | ||
|
||
```typescript | ||
import { makeExecutableSchema } from "graphql-tools"; | ||
|
||
const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
|
||
const schema = makeExecutableSchema({ typeDefs, resolvers }); | ||
``` | ||
|
||
Or even with other libraries that expect the schema info in that shape, like [`apollo-link-state`](https://github.com/apollographql/apollo-link-state): | ||
|
||
```typescript | ||
import { withClientState } from "apollo-link-state"; | ||
|
||
const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
|
||
const stateLink = withClientState({ | ||
// ...other options like `cache` | ||
typeDefs, | ||
resolvers, | ||
}); | ||
|
||
// ...the rest of `ApolloClient` initialization code | ||
``` | ||
|
||
Be aware that some of the TypeGraphQL features (i.a. [query complexity](complexity.md)) might not work with the `buildTypeDefsAndResolvers` approach because they use some low-level `graphql-js` features. |
38 changes: 38 additions & 0 deletions
38
website/versioned_docs/version-1.0.0-rc.1/browser-usage.md
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
--- | ||
title: Browser usage | ||
id: version-1.0.0-rc.1-browser-usage | ||
original_id: browser-usage | ||
--- | ||
|
||
## Using classes in a client app | ||
|
||
Sometimes we might want to use the classes we've created and annotated with TypeGraphQL decorators, in our client app that works in the browser. For example, reusing the args or input classes with `class-validator` decorators or the object type classes with some helpful custom methods. | ||
|
||
Since TypeGraphQL is a Node.js framework, it doesn't work in a browser environment, so we may quickly get an error, e.g. `ERROR in ./node_modules/fs.realpath/index.js`, while trying to build our app with Webpack. To correct this, we have to configure Webpack to use the decorator shim instead of the normal module. We simply add this plugin code to our webpack config: | ||
|
||
```js | ||
module.exports = { | ||
// ... the rest of the webpack config | ||
plugins: [ | ||
// ... here are any other existing plugins that we already have | ||
new webpack.NormalModuleReplacementPlugin(/type-graphql$/, resource => { | ||
resource.request = resource.request.replace(/type-graphql/, "type-graphql/dist/browser-shim.js"); | ||
}), | ||
]; | ||
} | ||
``` | ||
|
||
However, in some TypeScript projects like the ones using Angular, which AoT compiler requires that a full `*.ts` file is provided instead of just a `*.js` and `*.d.ts` files, to use this shim we have to simply set up our TypeScript configuration in `tsconfig.json` to use this file instead of a normal TypeGraphQL module: | ||
|
||
```json | ||
{ | ||
"compilerOptions": { | ||
"baseUrl": ".", | ||
"paths": { | ||
"type-graphql": ["./node_modules/type-graphql/dist/browser-shim.ts"] | ||
} | ||
} | ||
} | ||
``` | ||
|
||
Thanks to this, our bundle will be much lighter as we don't need to embed the whole TypeGraphQL library code in our app. |
101 changes: 101 additions & 0 deletions
101
website/versioned_docs/version-1.0.0-rc.1/complexity.md
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
--- | ||
title: Query complexity | ||
id: version-1.0.0-rc.1-complexity | ||
original_id: complexity | ||
--- | ||
|
||
A single GraphQL query can potentially generate a huge workload for a server, like thousands of database operations which can be used to cause DDoS attacks. In order to limit and keep track of what each GraphQL operation can do, `TypeGraphQL` provides the option of integrating with Query Complexity tools like [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity). | ||
|
||
This cost analysis-based solution is very promising, since we can define a “cost” per field and then analyze the AST to estimate the total cost of the GraphQL query. Of course all the analysis is handled by `graphql-query-complexity`. | ||
|
||
All we must do is define our complexity cost for the fields, mutations or subscriptions in `TypeGraphQL` and implement `graphql-query-complexity` in whatever GraphQL server that is being used. | ||
|
||
## How to use | ||
|
||
First, we need to pass `complexity` as an option to the decorator on a field, query or mutation. | ||
|
||
Example of complexity | ||
|
||
```typescript | ||
@ObjectType() | ||
class MyObject { | ||
@Field({ complexity: 2 }) | ||
publicField: string; | ||
|
||
@Field({ complexity: ({ args, childComplexity }) => childComplexity + 1 }) | ||
complexField: string; | ||
} | ||
``` | ||
|
||
The `complexity` option may be omitted if the complexity value is 1. | ||
Complexity can be passed as an option to any `@Field`, `@FieldResolver`, `@Mutation` or `@Subscription` decorator. If both `@FieldResolver` and `@Field` decorators of the same property have complexity defined, then the complexity passed to the field resolver decorator takes precedence. | ||
|
||
In the next step, we will integrate `graphql-query-complexity` with the server that expose our GraphQL schema over HTTP. | ||
You can use it with `express-graphql` like [in the lib examples](https://github.com/slicknode/graphql-query-complexity/blob/b6a000c0984f7391f3b4e886e3df6a7ed1093b07/README.md#usage-with-express-graphql), however we will use Apollo Server like in our other examples: | ||
|
||
```typescript | ||
async function bootstrap() { | ||
// ...build TypeGraphQL schema as always | ||
|
||
// Create GraphQL server | ||
const server = new ApolloServer({ | ||
schema, | ||
// Create a plugin that will allow for query complexity calculation for every request | ||
plugins: [ | ||
{ | ||
requestDidStart: () => ({ | ||
didResolveOperation({ request, document }) { | ||
/** | ||
* This provides GraphQL query analysis to be able to react on complex queries to your GraphQL server. | ||
* This can be used to protect your GraphQL servers against resource exhaustion and DoS attacks. | ||
* More documentation can be found at https://github.com/ivome/graphql-query-complexity. | ||
*/ | ||
const complexity = getComplexity({ | ||
// Our built schema | ||
schema, | ||
// To calculate query complexity properly, | ||
// we have to check only the requested operation | ||
// not the whole document that may contains multiple operations | ||
operationName: request.operationName, | ||
// The GraphQL query document | ||
query: document, | ||
// The variables for our GraphQL query | ||
variables: request.variables, | ||
// Add any number of estimators. The estimators are invoked in order, the first | ||
// numeric value that is being returned by an estimator is used as the field complexity. | ||
// If no estimator returns a value, an exception is raised. | ||
estimators: [ | ||
// Using fieldExtensionsEstimator is mandatory to make it work with type-graphql. | ||
fieldExtensionsEstimator(), | ||
// Add more estimators here... | ||
// This will assign each field a complexity of 1 | ||
// if no other estimator returned a value. | ||
simpleEstimator({ defaultComplexity: 1 }), | ||
], | ||
}); | ||
// Here we can react to the calculated complexity, | ||
// like compare it with max and throw error when the threshold is reached. | ||
if (complexity >= 20) { | ||
throw new Error( | ||
`Sorry, too complicated query! ${complexity} is over 20 that is the max allowed complexity.`, | ||
); | ||
} | ||
// And here we can e.g. subtract the complexity point from hourly API calls limit. | ||
console.log("Used query complexity points:", complexity); | ||
}, | ||
}), | ||
}, | ||
], | ||
}); | ||
|
||
// ...start the server as always | ||
} | ||
``` | ||
|
||
And it's done! 😉 | ||
|
||
For more info about how query complexity is computed, please visit [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity). | ||
|
||
## Example | ||
|
||
See how this works in the [simple query complexity example](https://github.com/MichalLytek/type-graphql/tree/master/examples/query-complexity). |
Oops, something went wrong.