Skip to content

Commit

Permalink
release: 1.0.0-rc.1
Browse files Browse the repository at this point in the history
  • Loading branch information
MichalLytek committed May 3, 2020
1 parent b2822d8 commit b815600
Show file tree
Hide file tree
Showing 24 changed files with 2,839 additions and 3 deletions.
8 changes: 5 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# Changelog and release notes

## Unreleased
<!-- ## Unreleased -->
<!-- here goes all the unreleased changes descriptions -->

## v1.0.0-rc.1
### Features
- **Breaking Change**: emit in schema only types actually used by provided resolvers classes (#415)
- **Breaking Change**: update `graphql-js` peer dependency to `^15.0.0`
- **Breaking Change**: update `graphql-query-complexity` dependency to `^0.5.0` and drop support for `fieldConfigEstimator` (use `fieldExtensionsEstimator` instead)
- **Breaking Change**: introduce `sortedSchema` option in `PrintSchemaOptions` and emit sorted schema file by default
- **Breaking Change**: make `class-validator` an optional, peer dependency of version `>=0.12.0` (#366)
- **Breaking Change**: remove deprecated direct array syntax for declaring union types
- **Breaking Change**: remove `CannotDetermineTypeError` and make other error messages more detailed and specific
- update `TypeResolver` interface to match with `GraphQLTypeResolver` from `graphql-js`
- add basic support for directives with `@Directive()` decorator (#369)
Expand All @@ -19,10 +20,10 @@
- add `{ autoRegisterImplementations: false }` option to prevent automatic emitting in schema all the object types that implements used interface type (#595)
- allow interfaces to implement other interfaces (#602)
### Fixes
- **Breaking Change**: stop returning null for `GraphQLTimestamp` and `GraphQLISODateTime` scalars when returned value is not a `Date` instance - now it throws explicit error instead
- refactor union types function syntax handling to prevent possible errors with circular refs
- fix transforming and validating nested inputs and arrays (#462)
- remove duplicated entries for resolver classes that use inheritance (#499)
- **Breaking Change**: stop returning null for `GraphQLTimestamp` and `GraphQLISODateTime` scalars when returned value is not a `Date` instance - now it throws explicit error instead
- fix using `name` option on interface fields (#567)
- fix not calling `authChecker` during subscribe phase for subscriptions (#578)
- fix using shared union type in multiple schemas
Expand All @@ -33,6 +34,7 @@
### Others
- **Breaking Change**: change build config to ES2018 - drop support for Node.js < 10.3
- **Breaking Change**: remove deprecated `DepreciationOptions` interface
- **Breaking Change**: remove deprecated direct array syntax for declaring union types

## v0.17.6
### Fixes
Expand Down
62 changes: 62 additions & 0 deletions website/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,68 @@
},
"version-0.17.6/version-0.17.6-custom-decorators": {
"title": "Custom decorators"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-bootstrap": {
"title": "Bootstrapping"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-browser-usage": {
"title": "Browser usage"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-complexity": {
"title": "Query complexity"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-custom-decorators": {
"title": "Custom decorators"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-dependency-injection": {
"title": "Dependency injection"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-directives": {
"title": "Directives"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-emit-schema": {
"title": "Emitting the schema SDL"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-examples": {
"title": "Examples",
"sidebar_label": "List of examples"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-extensions": {
"title": "Extensions"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-generic-types": {
"title": "Generic Types"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-getting-started": {
"title": "Getting started"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-installation": {
"title": "Installation"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-interfaces": {
"title": "Interfaces"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-middlewares": {
"title": "Middleware and guards"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-performance": {
"title": "Performance"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-resolvers": {
"title": "Resolvers"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-subscriptions": {
"title": "Subscriptions"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-types-and-fields": {
"title": "Types and Fields"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-unions": {
"title": "Unions"
},
"version-1.0.0-rc.1/version-1.0.0-rc.1-validation": {
"title": "Argument and Input validation",
"sidebar_label": "Validation"
}
},
"links": {
Expand Down
132 changes: 132 additions & 0 deletions website/versioned_docs/version-1.0.0-rc.1/bootstrap.md
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 website/versioned_docs/version-1.0.0-rc.1/browser-usage.md
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 website/versioned_docs/version-1.0.0-rc.1/complexity.md
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).
Loading

0 comments on commit b815600

Please sign in to comment.